使用本机PHP7.x将XML数组转换为json/stdClass,包括所有属性
我有一些复杂的XML结构,我想在不知道XML结构的情况下将其转换为stdClass/Json。大多数情况下,这两行代码都有效,但一旦我有了一个项目列表,它就不一定能得到我期望的结果,例如:使用本机PHP7.x将XML数组转换为json/stdClass,包括所有属性,php,xml,php-7.0,Php,Xml,Php 7.0,我有一些复杂的XML结构,我想在不知道XML结构的情况下将其转换为stdClass/Json。大多数情况下,这两行代码都有效,但一旦我有了一个项目列表,它就不一定能得到我期望的结果,例如: <?php $response = <<<EOF <?xml version="1.0" encoding="UTF-8"?> <Foo Id="1234"> <Bar Type=&qu
<?php
$response = <<<EOF
<?xml version="1.0" encoding="UTF-8"?>
<Foo Id="1234">
<Bar Type="typ">
<Prop1 Attrb="value1" />
<Prop2 Attrb="value2" />
<Baz>
<Prop Id="111">value1</Prop>
<Prop Id="222">value2</Prop>
</Baz>
</Bar>
</Foo>
EOF;
$xml = new SimpleXMLElement($response);
echo json_encode($xml, JSON_PRETTY_PRINT);
这很好,除了Baz中的Prop之外,我有一个我需要的属性,但在这里它不见了。我想要这样的东西:
{
"@attributes":{
"Id":"1234"
},
"Bar":{
"@attributes":{
"Type":"typ"
},
"Prop1":{
"@attributes":{
"Attrb":"value1"
}
},
"Prop2":{
"@attributes":{
"Attrb":"value2"
}
},
"Baz":{
"Prop":[
{
"@attributes":{
"Id":"111"
},
"@value":"value1"
},
{
"@attributes":{
"Id":"222"
},
"@value":"value2"
}
]
}
}
}
{
"@attributes":{
"Id":"1234"
},
"Bar":{
"@attributes":{
"Type":"typ"
},
"Prop1":{
"@attributes":{
"Attrb":"value1"
}
},
"Prop2":{
"@attributes":{
"Attrb":"value2"
}
},
"Baz":{
"Prop":[
{
"@attributes":{
"Id":"111"
},
"@value":"value1"
},
{
"@attributes":{
"Id":"222"
},
"@value":"value2"
}
]
}
}
}