【发布时间】:2020-05-11 13:59:54
【问题描述】:
我正在尝试在 php 中将 xml 转换为 json。我尝试使用 json_encode。但是在 PHP 7.2 和 PHP 7.4 环境中结果是不同的。请参阅以下示例。
示例 1
$xmlString = '<properties><property name="width">20</property><property name="height">100</property></properties>';
echo json_encode(simplexml_load_string($xmlString));
PHP 7.4 中的输出:每个节点都有@attributes
{"property":[{"@attributes":{"name":"width"},"0":"20"},{"@attributes":{"name":"height"},"0":"100"}]}
PHP 7.2 中的输出:@attributes 不存在
{"property":["20","100"]}
示例 2
$xmlString = '<property name="width">20</property>';
echo json_encode(simplexml_load_string($xmlString));
在 PHP 7.2 和 PHP 7.4 环境中的输出:@attributes 在那里
{"@attributes":{"name":"width"},"0":"20"}
示例 3
$xmlString = '<properties rank="1"><property name="width">20</property></properties>';
echo json_encode(simplexml_load_string($xmlString));
PHP 7.4 中的输出:每个节点都有@attributes
{"@attributes":{"rank":"1"},"property":{"@attributes":{"name":"width"},"0":"20"}}
PHP 7.2 中的输出:@attributes 仅适用于父节点
{"@attributes":{"rank":"1"},"property":"20"}
问题
- 为什么上述三个示例在不同环境下的json_encode行为不同?
- 如果我总是想要 PHP 7.2 环境中给出的输出(即使在 PHP 7.4 环境中也没有 @attribute 属性),我应该如何将 SimpleXMLElement 对象转换为 JSON 格式?
【问题讨论】: