Site icon Nabtron

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.

Converting

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 = '
<cars>
  <make name="honda">
    <exotic>accord</exotic>
    <tuner>civic 95</tuner>
    <tuner>civic 2004</tuner>
  </make>
</cars>

‘;

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); :

Array
(
    [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: http://gaarf.info/2009/08/13/xml-string-to-php-array/

Exit mobile version