I have some xml, this is a simple version of it.
- item one
- item two
You can go the route with json_encode and json_decode and you can add the stuff you're missing because that json_encode-ing follows some specific rules with SimpleXMLElement.
If you're interested into the rules and their details, I have written two blog-posts about it:
For you perhaps more interesing is the third part which shows how you can modify the json serialization and provide your own format (e.g. to preserve the attributes):
It ships with a full blown example, here is an excerpt in code:
$xml = '
- item one
- item two
';
$obj = simplexml_load_string($xml, 'JsonXMLElement');
echo $json = json_encode($obj, JSON_PRETTY_PRINT), "\n";
print_r(json_decode($json, TRUE));
Output of JSON and the array is as following, note that the attributes are part of it:
{
"items": {
"item": [
{
"@attributes": {
"abc": "123"
},
"@text": "item one"
},
{
"@attributes": {
"abc": "456"
},
"@text": "item two"
}
]
}
}
Array
(
[items] => Array
(
[item] => Array
(
[0] => Array
(
[@attributes] => Array
(
[abc] => 123
)
[@text] => item one
)
[1] => Array
(
[@attributes] => Array
(
[abc] => 456
)
[@text] => item two
)
)
)
)