How to convert XML into an associative array in PHP?

The other day I wanted to convert an XML document into an associative array for a specific task.
I knew I could get relevant information using XPath and few lines of code tweaks as well.

But still I was looking for a different but easy way of doing it.

So I went to Google and typed in 'How to convert XML into an associative array?'  in the text box and pressed 'Search'.





On the results page I found that the same question was posted already in http://stackoverflow.com site as well. So then I just scan that page where the solutions were given to this question.

There were a number of responses. Out of all one particulate solution captured my attention.
It was very short, effective and very simple solution. It only got a few lines of codes. But does the job very well.
I found it very very useful to me.
I hope this code may help your coding needs as well, Therefore sharing it with you guys :)


$xmlfile = file_get_contents("Name/or/path/to/xml/file/");
$ob = simplexml_load_string($xmlfile);
$json = json_encode($ob);
$array = json_decode($json, true);

var_dump($array);
 
Thanks for dropping by,

No comments:

Post a Comment