php - 引用 : Why are my "special" Unicode characters encoded weird using json_encode?

标签 php unicode utf-8 json

当使用“特殊”Unicode 字符时,它们在编码为 JSON 时会变成奇怪的垃圾:

php > echo json_encode(['foo' => '馬']);
{"foo":"\u99ac"}

为什么?我的编码有问题吗?

(这是一个一劳永逸澄清主题的引用题,因为这个问题反复出现。)

最佳答案

首先:这里没有任何问题。这就是字符可以在 JSON 中编码的方式。它在 the official standard .它基于如何在 Javascript ECMAScript ( section 7.8.4 "String Literals" ) 中形成字符串文字,并描述如下:

Any code point may be represented as a hexadecimal number. The meaning of such a number is determined by ISO/IEC 10646. If the code point is in the Basic Multilingual Plane (U+0000 through U+FFFF), then it may be represented as a six-character sequence: a reverse solidus, followed by the lowercase letter u, followed by four hexadecimal digits that encode the code point. [...] So, for example, a string containing only a single reverse solidus character may be represented as "\u005C".

简而言之:任何字符都可以编码为\u....,其中....是字符的Unicode代码点(或代码UTF-16 代理项对的一半的点,对于 BMP 之外的字符)。

"馬"
"\u99ac"

这两个字符串文字表示完全相同的字符,它们是绝对等价的。当这些字符串文字被兼容的 JSON 解析器解析时,它们都将生成字符串“马”。它们看起来不一样,但在 JSON 数据编码格式中意思是一样的。

PHP 的 json_encode最好使用 \u.... 转义序列对非 ASCII 字符进行编码。从技术上讲,它不必,但确实如此。结果是完全有效的。如果您更喜欢在 JSON 中使用文字字符而不是转义序列,您可以在 PHP 5.4 或更高版本中设置 JSON_UNESCAPED_UNICODE 标志:

php > echo json_encode(['foo' => '馬'], JSON_UNESCAPED_UNICODE);
{"foo":"馬"}

强调:这只是一个偏好,没有必要以任何方式在 JSON 中传输“Unicode 字符”。

关于php - 引用 : Why are my "special" Unicode characters encoded weird using json_encode?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22745662/

相关文章:

javascript - 与 Javascript 共享 PHP session

php - 以下正确的字符编码是什么

php - sonataIntlBundle 问题 - 我无法使用 composer 安装

php - 为什么 fgetcsv 跳过第一行?

python在html中显示unicode

python - Unicode Django URL 参数

python - UnicodeEncodeError : 'ascii' codec can't encode character u'\xe9' in position 7: ordinal not in range(128)

linux - 在 perl 上打印包含 utf-8 字节序列的字符串

asp-classic - 经典 ASP 文本替换和 UTF-8 编码

php - 如何运行包含来自 heroku 上托管的 php 库的 python 脚本?