我在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(强调矿)
所有Unicode字符都可以放在引号内,但必须转义的字符除外:引号、反向实线和控制字符(U+0000到U+001F)。
Newline('n
)是UTF-8中的U+000A
,因此PHP会尽职尽责地将其转换回相应的JS等价
PHP使用此RFC进行json_encode
PHP实现了原始»RFC 4627中指定的JSON超集,它还将对标量类型和NULL进行编码和解码。
正如我在评论中所指出的,所有版本的PHP,回到5.2,都是这样做的(演示)