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