【问题标题】:PHP - html_entity_decode to entire arrayPHP - html_entity_decode 到整个数组
【发布时间】:2021-02-21 01:38:09
【问题描述】:

我正在获取 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']; ?>

string_key 的值包含我网站的英语或俄语翻译,具体取决于它是哪个 JSON 数组。

问题:

当我上传包含西里尔字符(俄语)的 JSON 文件时,会发生这种情况:

хорошо --> &#1093;&#1086;&#1088;&#1086;&#1096;&#1086;

每个西里尔字符都会被转换为 HTML 实体。所以我发现我可以使用html_entity_decode() 来解决这个问题,但想象一下,为我的代码中的每个 单个&lt;?php echo $i18n[$arr]['string_key']; ?&gt; 调用执行此操作是多么耗时。没有办法解决吗?我尝试将$i18n 传递给html_entity_decode(),但它需要string,而不是array of strings。有什么想法吗?

我的 JSON 示例:

{
    "i18n_en":
    {
        "key0": "value0",
        "key1": "value1"
    },
    "i18n_ru":
    {
        "key0": "value0",
        "key1": "value1"
    }
}

【问题讨论】:

  • 你为什么在$_GET 值上调用htmlentitieshtmlentities 应该只在页面中显示一个值并且你不希望它被呈现为 HTML 时使用。
  • 我只是觉得这是防御黑客攻击的好习惯...也许我会删除这些调用。

标签: php html arrays json


【解决方案1】:

如果你想在一个字符串数组上运行html_entity_decode(),你可以使用array_map。像这样:

$resultArray = array_map("html_entity_decode", $inputArray);

【讨论】:

  • 我明白了:Warning: html_entity_decode() expects parameter 1 to be string, array given...
  • 不是html_entities_decode,而是html_entity_decode
【解决方案2】:

一旦你设置了$arr,你就可以通过foreach循环将html_entities_decode()应用于指定语言的每个字符串。

类似这样的:

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);
}

编辑。修复Warning: Illegal string offset 'i18n_en'的两种可能解决方案。

1:

foreach ($i18n[$arr] as &$myString) {
    if(isset($myString)){
        $myString = html_entity_decode($myString);
    }
}
foreach ($i18n[$arr] as &$myString) {
    $myString = html_entity_decode($myString, ENT_COMPAT, 'UTF-8');
}

或者也许,两者结合。请让我知道这是否有效。

【讨论】:

  • 这可行,但如何echo 新字符串?我尝试做echo $myString[$arr]['key'];,但我得到Warning: Illegal string offset 'i18n_en'
  • 嗯...可能其中一些字符串是空的?
  • 是的,大约 2~3 个俄语字符串是空的。
  • 好的,我对这个警告有两个想法,让我把它放在答案中以使其易于阅读。约翰尼·P。
  • 如果我尝试将其称为$myString[$arr]['slang'],它不会。而且我不知道有什么其他的称呼方式。如果我只是调用echo $myString;,我会从 JSON 数组中得到一个完全随机的字符串。
【解决方案3】:

您可以使用 PHP 的 array_map() 函数对数组中的每个项目调用函数。下面是一个例子。

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

function decode($toDecode) {
    return html_entity_decode($toDecode);
}

【讨论】:

    猜你喜欢
    • 2011-06-06
    • 1970-01-01
    • 2016-02-03
    • 2014-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多