I want to convert and XML file to JSON with PHP. The XML file looks like this:
<content>
<!-- other elements... -->
<box id="1">
<a>...</a>
<b>...</b>
<c>...</c>
</box>
<box id="2">
<a>...</a>
<b>...</b>
<c>...</c>
</box>
<box id="3">
<a>...</a>
<b>...</b>
<c>...</c>
</box>
<!-- more <box> elements... -->
<!-- other elements... -->
</content>
I am using this simple PHP script:
// Open XML file with SimpleXML.
$xml = simplexml_load_file('file.xml');
// Convert XML content to JSON.
$json = json_encode($xml);
// Output JSON.
echo $json;
I get the full content of the XML file as JSON output, however I need to modify the script to:
<box>
elements, not the complete file.This is an example of what I want to get as output:
[{"a":"...","b":"...","c":"..."},
{"a":"...","b":"...","c":"..."},
{"a":"...","b":"...","c":"..."}]
Please help me, how can I do this? what is the best practice?
Thanks in advance.
If the node name (box) doesn't change, you could use xpath:
$xml = simplexml_load_file('test.xml');
$arr = (array) $xml -> xpath('box');
...But because each box has an id, this led to a kind of madness:
$final = array();
foreach ($arr as $box) {
$box = (array) $box;
unset($box['@attributes']);
$final[] = $box;
}
I was going to look for a better way, but I began seeing a floating dagger so I gave up. As is, you just need to json_encode the $final array. Godspeed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With