PHP-html_实体_解码为整个数组

PHP-html_实体_解码为整个数组,php,html,arrays,json,Php,Html,Arrays,Json,我正在获取JSON数据以便在我的网站中使用,我需要回显它,如下所示: <?php $json = file_get_contents("/lang/translator.php"); // uses preg_replace to remove whitespace/newlines from my actual json file and then echo's it $i18n = json_decode($json, true); if (htmlentit

我正在获取JSON数据以便在我的网站中使用,我需要回显它,如下所示:

<?php
    $json = file_get_contents("/lang/translator.php"); // uses preg_replace to remove whitespace/newlines from my actual json file and then echo's it
    $i18n = json_decode($json, true);

    if (htmlentities($_GET['lang'], ENT_QUOTES) == 'en')
    {
        $arr = 'i18n_en';
    }
    else if (htmlentities($_GET['lang'], ENT_QUOTES) == 'ru')
    {
        $arr = 'i18n_ru';
    }
?>
<?php echo $i18n[$arr]['string_key']; ?>
if (htmlentities($_GET['lang'], ENT_QUOTES) == 'en')
{
    $arr = 'i18n_en';
}
else if (htmlentities($_GET['lang'], ENT_QUOTES) == 'ru')
{
    $arr = 'i18n_ru';
}

foreach ($i18n[$arr] as &$myString) {
    $myString = html_entity_decode($myString);
}
每一个西里尔字符都会转换为HTML实体。所以我发现我可以使用html_entity_decode来解决这个问题,但是想象一下,对于代码中的每个调用,这样做是多么耗时。没有办法解决这个问题吗?我尝试将$i18n传递给html_entity_decode,但它需要的是字符串,而不是字符串数组。有什么想法吗

我的JSON示例:

{
    "i18n_en":
    {
        "key0": "value0",
        "key1": "value1"
    },
    "i18n_ru":
    {
        "key0": "value0",
        "key1": "value1"
    }
}
可以使用PHP的array_map函数对数组中的每个项调用函数。下面可以看到一个例子

$decodedArray = array_map("decode",$i18n);

function decode($toDecode) {
    return html_entity_decode($toDecode);
}
如果要在字符串数组上运行html_entity_decode,可以使用Array_map。像这样:

$resultArray=数组\映射HTML \实体\解码,$inputArray

一旦设置了$arr,就可以使用foreach循环对指定语言中的每个字符串应用html\u entities\u decode

大概是这样的:

<?php
    $json = file_get_contents("/lang/translator.php"); // uses preg_replace to remove whitespace/newlines from my actual json file and then echo's it
    $i18n = json_decode($json, true);

    if (htmlentities($_GET['lang'], ENT_QUOTES) == 'en')
    {
        $arr = 'i18n_en';
    }
    else if (htmlentities($_GET['lang'], ENT_QUOTES) == 'ru')
    {
        $arr = 'i18n_ru';
    }
?>
<?php echo $i18n[$arr]['string_key']; ?>
if (htmlentities($_GET['lang'], ENT_QUOTES) == 'en')
{
    $arr = 'i18n_en';
}
else if (htmlentities($_GET['lang'], ENT_QUOTES) == 'ru')
{
    $arr = 'i18n_ru';
}

foreach ($i18n[$arr] as &$myString) {
    $myString = html_entity_decode($myString);
}
编辑。修复警告的两种可能的解决方案:非法字符串偏移量“i18n_en”

1:


或者,两者兼而有之。请让我知道这是否有效。

我知道:警告:html\u entity\u decode要求参数1为字符串,给定数组…这不是html\u entities\u decode,而是html\u entity\u decode。这有效,但如何回显新字符串?我试着做echo$myString[$arr]['key'];但我得到警告:非法的字符串偏移量'i18n_en'。嗯。。。也许这些字符串中有一些是空的吗?是的,大约有2~3个俄文字符串是空的。好吧,我有两个关于这个警告的想法,让我把它放在答案中,以便于阅读。如果我试着把它叫做$myString[$arr]['slang',],它不会。我不知道还有什么别的说法。如果我只调用echo$myString;我从JSON数组中得到一个完全随机的字符串。为什么要对$\u get值调用htmlentities?只有在页面中显示值时才应使用htmlentities,并且您不希望将其呈现为HTML。我只是觉得这是抵御黑客攻击的一个好方法。。。也许我会取消这些电话。