【问题标题】:PHP convert XML with mixed array children to JSON keeping the child orderPHP 将混合数组子元素的 XML 转换为 JSON 以保持子元素的顺序
【发布时间】:2016-12-08 09:20:10
【问题描述】:

我知道如何使用SimpleXML将XML转换为JSON,但是当同一个节点有多种子节点时,如何保存订单信息?

$xml = simplexml_load_string('
<root>
    <a id="0"></a>
    <b id="0"></b>
    <b id="1"></b>
    <a id="1"></a>
    <a id="2"></a>
</root>
');
echo json_encode($xml->children());

代码打印如下:

{
  "a": [
    {
      "@attributes": {
        "id": "0"
      }
    },
    {
      "@attributes": {
        "id": "1"
      }
    },
    {
      "@attributes": {
        "id": "2"
      }
    }
  ],
  "b": [
    {
      "@attributes": {
        "id": "0"
      }
    },
    {
      "@attributes": {
        "id": "1"
      }
    }
  ]
}    

因此我不知道元素最初来自哪里,无论是按a, b, b, a, a 还是a, a, b, b, a 的顺序

所以我想知道是否有办法将该 XML 转换为 JSON 来保留这些信息?可能结果是这样的:

[
  {
    "tag": "a",
    "@attributes": {
      "id": "0"
    }
  },
  {
    "tag": "b",
    "@attributes": {
      "id": "0"
    }
  },
  {
    "tag": "b",
    "@attributes": {
      "id": "1"
    }
  },
  {
    "tag": "a",
    "@attributes": {
      "id": "1"
    }
  },
  {
    "tag": "a",
    "@attributes": {
      "id": "2"
    }
  }
]    

【问题讨论】:

    标签: php json xml simplexml


    【解决方案1】:
    $xml = <<<'XML'
    <root>
        <a id="0"></a>
        <b id="0"></b>
        <b id="1"></b>
        <a id="1"></a>
        <a id="2"></a>
    </root>
    XML;
    
    $xe = simplexml_load_string($xml);
    $a = $xe->xpath('*');
    $a = array_map(function ($e) {
      $item = (array) $e;
      $item['tag'] = $e->getName();
      return $item;
    }, $a);
    echo json_encode($a, JSON_PRETTY_PRINT);
    

    输出

    [
        {
            "@attributes": {
                "id": "0"
            },
            "tag": "a"
        },
        {
            "@attributes": {
                "id": "0"
            },
            "tag": "b"
        },
        {
            "@attributes": {
                "id": "1"
            },
            "tag": "b"
        },
        {
            "@attributes": {
                "id": "1"
            },
            "tag": "a"
        },
        {
            "@attributes": {
                "id": "2"
            },
            "tag": "a"
        }
    ]
    

    【讨论】:

    • 非常感谢!但是如果 XML 有命名空间呢?然后xpath返回空数组
    • @I2_wadxm,星号似乎也适用于命名空间的 XML。 Example。但是可以使用 DOM 扩展而不是 SimpleXML。 DOMXPath 允许注册命名空间:$xp-&gt;registerNamespace('myns', 'http://...');,然后在 XPath 表达式中使用它:/root/myns:*
    【解决方案2】:

    只需遍历子元素并将tag 设置为每个元素。像这样的:

    $result = [];
    foreach($xml->children() as $tag => $e) {
        $tagged = json_decode(json_encode($e));
        $tagged->tag = $tag;
        $result[] = $tagged;
    }
    echo json_encode($r);
    

    【讨论】:

      猜你喜欢
      • 2016-06-09
      • 1970-01-01
      • 2012-02-24
      • 2022-01-13
      • 1970-01-01
      • 2021-08-11
      • 1970-01-01
      • 2020-05-19
      • 2017-09-30
      相关资源
      最近更新 更多