Convert XML string to PHP Array

PHP programmers usually require to convert xml data to php array to store or use it in their classes methods and functions.

Now its a different discussion why can’t they use xml data directly without having to convert xml to php array. In a project today, I needed to convert the xml data to php array too.


How to convert xml data to php array

Trick to convert the xml data to php array is pretty much simple. Look at the following example:

XML string:

$xml = '
  <make name="honda">
    <tuner>civic 95</tuner>
    <tuner>civic 2004</tuner>


So now to convert this xml to php array we will use this code :

$ourarray = json_decode(json_encode((array) simplexml_load_string($xml)),1);

The resulting php array which we just converted from xml string will give this result on prin_r($ourarray); :

    [show] => Array
            [@attributes] => Array
                    [make] => honda
            [exotic] => Brian
            [tuner] => Array
                    [0] => civic 95
                    [1] => civic 2004

Update: Incase you have CDATA node in your array you can get in trouble as it will result in an empty array position at that spot. This can be fixed by following code provided here:

Leave a Reply

Your email address will not be published.