Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert XML to JSON without attributes using PHP?

Tags:

json

php

xml

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:

  • Get only JSON for the <box> elements, not the complete file.
  • Get JSON without element attributes.

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.

like image 216
VerizonW Avatar asked Jun 26 '26 14:06

VerizonW


1 Answers

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.

like image 58
sdleihssirhc Avatar answered Jun 28 '26 04:06

sdleihssirhc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!