PHP将具有混合数组子级的XML转换为JSON以保持子顺序

时间:2016-12-08 09:20:10

标签: php json xml simplexml

我知道如何使用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"
    }
  }
]    

2 个答案:

答案 0 :(得分: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"
    }
]

答案 1 :(得分:0)

只需迭代子项并将tag设置为每个元素。像这样:

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