我在 PHP 5.6 上遇到过这种行为(在 PHP 5.4 到 7.0 中也是相同的)。
$note = new SimpleXMLElement('<Note></Note>');
$note->addChild("string0", 'just a string');
$note->addChild("string1", "abc\n\n\n");
$note->addChild("string2", "\tdef");
$note->addChild("string3", "\n\n\n");
$note->addChild("string4", "\t\n");
$json = json_encode($note, JSON_PRETTY_PRINT);
print($json);
输出:
{
"string0": "just a string",
"string1": "abc\n\n\n",
"string2": "\tdef",
"string3": {
"0": "\n\n\n"
},
"string4": {
"0": "\t\n"
}
}
这种行为背后一定有原因,我想明白了。而且,如果您知道一种方法可以强制它对文本字符串和空格以相同的方式运行,我将不胜感激您分享您的想法!
编辑。这是您可以运行的片段:http://sandbox.onlinephpfunctions.com/code/d797623553c11b7a7648340880a92e98b19d1925
最佳答案
这来自RFC 4627 (强调我的)
All Unicode characters may be placed within the quotation marks except for the characters that must be escaped: quotation mark, reverse solidus, and the control characters (U+0000 through U+001F).
Newline(\n
) 是 UTF-8 中的 U+000A
,因此 PHP 尽职尽责地将其转换回相应的 JS 等价物
PHP 将此 RFC 用于 json_encode
PHP implements a superset of JSON as specified in the original » RFC 4627 - it will also encode and decode scalar types and NULL.
正如我在评论中指出的那样,所有版本的 PHP,回到 5.2,都是这样做的(Demo)
关于php - 为什么将空白字符串的 json_encode 添加到数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38486186/