【问题标题】:PHP json_encode of SimpleXMLELement gives different results in different environmentsSimpleXMLELement 的 PHP json_encode 在不同的环境下给出不同的结果
【发布时间】: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"}

问题

  1. 为什么上述三个示例在不同环境下的json_encode行为不同?
  2. 如果我总是想要 PHP 7.2 环境中给出的输出(即使在 PHP 7.4 环境中也没有 @attribute 属性),我应该如何将 SimpleXMLElement 对象转换为 JSON 格式?

【问题讨论】:

    标签: php json xml


    【解决方案1】:

    看起来这种行为变化发生在 7.3.17 / 7.4.5(参见 this example)并且是由于 bug fix。您可以在 7.4.57.3.17 的变更日志的 SimpleXML 部分确认这一点。

    恢复该行为的最简单方法可能是降级您的 PHP 版本。

    可以使用simplexml_load_string()$options 参数来更改其行为方式。我会咨询 manual page 及其 cmets 以了解更多信息。

    尽管有该选项,您可能只需将 simplexml_load_string() 调用包装在您编写的另一个函数中,该函数将其返回值更改为您的偏好。

    【讨论】:

    • 看起来 FIX 现在做事正确,所以从长远来看,降级的建议似乎不是一个可行的解决方案
    • 非常感谢您的及时回复。看来我必须使用您的最后一个解决方案(将 simplexml_load_string() 调用包装在另一个函数中)
    • @RiggsFolly 同意,抱歉,我更倾向于将其作为可能的短期解决方案发布,直到可以编写出更好的解决方案。
    猜你喜欢
    • 2012-09-15
    • 1970-01-01
    • 2016-10-18
    • 2012-07-16
    • 2012-06-02
    • 2015-04-23
    • 2014-03-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多