简体   繁体   English

json_encode()UTF-8错误

[英]json_encode() UTF-8 error

I'm having some problem getting text with special characters (Swedish: "åäö") from the database. 我在从数据库中获取带有特殊字符的文本时遇到了一些问题(瑞典语:“åäö”)。

If I just do a normal query, 如果我只是进行普通查询,

"SELECT * FROM"  

and the echo out the result: echo显结果:

while($row = mysql_fetch_assoc($result))
{
    echo $row['text']; 
}

... the result is fine. ...结果很好。

However, when doing json_encode($array) , the special characters have been replaced: 但是,当执行json_encode($array) ,特殊字符已被替换:

{"id":"1","question":"fr\u00e5ga \u00e5\u00e4\u00f6"....

I don't know how many different things I tried, including converting the database to UTF-8, fields to utf8_general_ci , utf8_encode($string) , utf8_decode($string) , .... 我不知道我尝试了多少不同的操作,包括将数据库转换为UTF-8,将字段转换为utf8_general_ciutf8_encode($string)utf8_decode($string) ,...。

Your output is correct; 您的输出是正确的; that's how you're supposed to embed unicode characters in JSON. 这就是您应该在JSON中嵌入unicode字符的方式。

This behavior is by design. 此行为是设计使然。 Those are JSON Unicode escapes. 这些是JSON Unicode转义。

Any compliant JSON parser will parse them correctly. 任何兼容的JSON解析器都会正确解析它们。

$str='{"id":"1","question":"fr\u00e5ga \u00e5\u00e4\u00f6"}';
$obj=json_decode($str);
var_dump($obj);

Outputs this 输出这个

object(stdClass)#1 (2) {
  ["id"]=>
  string(1) "1"
  ["question"]=>
  string(13) "fråga åäö"
}

So all is well - you're just seeing the JSON encoding of Unicode characters. 一切都很好-您只是看到Unicode字符的JSON编码。

In PHP 5.4, you can pass JSON_UNESCAPED_UNICODE to json_encode, and you'll get back JSON with UTF-8 encoded chars (at least I believe so - haven't tested that yet) 在PHP 5.4中,您可以将JSON_UNESCAPED_UNICODE传递给json_encode,并且您将使用UTF-8编码的字符返回JSON(至少我相信是这样-尚未进行测试)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM