echo json_encode(['foo' => '馬']); {"foo":"\u99ac"} 为-6ren">
gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 22:56:17 25 4
gpt4 key购买 nike

当使用“特殊”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/26253224/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com