php - 为什么将空白字符串的 json_encode 添加到数组中?

标签 php json simplexml

我在 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/

相关文章:

php - 使用 INSERT 和 WHERE 进行 MySQLi 查询,可能吗?

php - WooCommerce 通过 AJAX 触发自定义电子邮件

Python性能调优: JSON to CSV,大文件

javascript - Phaser.io 加载时的 JSON 回调

PHP SimpleXML 到 JSON 编码单元素数组

xml - PHP 捕获 SimpleXMLElement 解析错误

php - 具有xpath和PHP的XML:如何访问条目属性的文本值

php - Laravel Forge 部署失败

php - 通过 if(!empty($_GET for Wordpress 进行 SQL 查询

Java 使用来自 Rest 服务 GET 的 JSON 列表