Download convert string to xml using php for windows 7 64

How to Convert XML File to Array in PHP

Converting XML File to PHP Array

Converting xml data into array is simpler than you think and we are going to take advantage of simplexml lib and json functions to complete the task with minimal code. Just take this below xml file as an example for our purpose.

Here is the php script to convert the above xml file to associative array.

We have written a php function xml2Array() that takes up the xml filename as argument and convert it into array.

The method simplexml_load_file($filename, "SimpleXMLElement", LIBXML_NOCDATA) converts the given XML file into a SimpleXMLElement object. Its second param SimpleXMLElement specifies the class name of the new object created. And the third param LIBXML_NOCDATA is a constant that tells to merge CDATA as text nodes. Learn more about the method here.

And the method json_encode($xmlstring) returns the JSON representation of the given object.

Finally json_decode($json, TRUE) decodes the given JSON string into an array or object. Providing the second param TRUE tells it to return an associative array.

Converting XML String to PHP Array

Alternatively if you have xml data as string and wish to convert to array, then you have to use this statement instead of loading from the file.

This converts a well-formed xml string to a simplexmlelement object. You have to change only this line and the rest of the code remains the same.

Thus with the help of this php script you can easily convert xml file or string to an array.

Do you find our tutorials helpful?

Now Like us on Facebook and get notified of our exclusive tutorials.