【问题标题】:Charset on JSON is not showing special characters, getting NULL insteadJSON 上的字符集不显示特殊字符,取而代之的是 NULL
【发布时间】:2015-11-07 14:32:54
【问题描述】:

我得到一个带有 JSON 但带有特殊字符的查询结果,它显示的是 NULL 而不是正确的结果。我已经尝试过array_map('utf8_encode'),但仍然遇到同样的错误。

代码:

if (mysql_num_rows($result) > 0) {
    // looping through all results
    // products node
   $response["reserves"] = array();

    while ($row = mysql_fetch_array($result)) {
        // temp user array
        $product = array();
        array_map('utf8_encode', $product);
        $product["id_reserve"] = $row["id_r"];
        $product["description"] = $row["d_reserve"];
        // push single product into final response array
        array_push($response["reserves"], $product);
    }
    // success
    $response["success"] = 1;

    // echoing JSON response
    echo json_encode($response);

【问题讨论】:

  • 您必须确保整个 Web 应用程序在任何地方都使用相同的字符集(DB、HTML、...),或者您也可以在回显之前将特殊字符替换为它们的值 - 例如“étrange”这个词会变成“\xc3\xa9trange”。
  • 感谢您的回答。 MySQL 数据库中的排序规则是“utf8_general_ci”,PHP 上的标头将字符集设置为 UTF8。 PHP 中的回显正确显示了字符,所以我认为这不是问题。还是谢谢。
  • 在 json_encode() 之前的回声应该没问题,但你的问题是在那之后。这就是为什么你得到一个NULL。只需在我的示例中尝试一些虚拟代码,您就会看到
  • 我想我不明白你...对不起。我尝试这样的事情:$product["description"] = "\xc3\xa9trange"。并且输出是:description":"\u00e9trange" 那是有问题的。但是我不知道你想说什么之后 json_encode()...
  • 尝试输入我的代码,然后在 json 编码后做一个回显:)

标签: php json null character utf


【解决方案1】:

(代表 OP 发布)。

要设置数组值 utf-8,函数 utf8_encode 必须放在 $row 之前。结果是:

$product["description"] = utf8_encode($row["d_reserve"]);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-08
    • 1970-01-01
    相关资源
    最近更新 更多