Today, I need to convert XML file into associative array to store in variable. So I have done a lot of googling and found several methods/views and library to convert XML object into Array, but in stack overflow – I have found below simple script to convert xml into array.I am using file_get_contents() php method to read xml file data into string.
Also checkout other related tutorials,
- Convert XML to Array in PHP Using XML2Array
- How To Convert XSD into Array Using PHP
- How To Convert XML To Associative Array
In this tutorial, I will let you know how to convert XML into array in php.
Step 1: Sample XML file
I have created below xml sample.xml
file, which will use to convert into array using PHP.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | <?xml version='1.0'?> <moleculedb> <molecule name='Benzine'> <symbol>ben</symbol> <code>A</code> </molecule> <molecule name='Water'> <symbol>h2o</symbol> <code>K</code> </molecule> <molecule name='Parvez'> <symbol>h2o</symbol> <code>K</code> </molecule> </moleculedb> |
Step 2: Convert sample.xml
File Into String
Now, I will use file_get_contents()
PHP method to read entire file into a string and store into $xmlfile
variable.
1 | $xmlfile = file_get_contents($path); |
Step 3: Convert string of XML into an Object,
We have xml file as an string, So Let’s convert this xml string into Objects.I will use simplexml_load_string()
php method to convert string of XML into an object.
1 | $ob= simplexml_load_string($xmlfile); |
Step 4: Encode XML Object Into JSON
I will encode XML object into JSON, below code will convert xml object into json string.
1 | $json = json_encode($ob); |
Step 5: Decode Json Object
Finally we will decode json to get array from json string.
1 | $configData = json_decode($json, true); |
Full Source Code
1 2 3 4 5 6 | $path = "sample.xml" $xmlfile = file_get_contents($path); $ob= simplexml_load_string($xmlfile); $json = json_encode($ob); $configData = json_decode($json, true); echo "<pre>":print_r($configData); |
$array = (array) simplexml_load_string($xmlfile);
Gets you the exact same result, without all the unnecessary code.
$array = (array) simplexml_load_string($xmlfile);
This doesn’t work for tags without content, like `
ok, i ll chek
you need to pass third parameter as LIBXML_NOCDATA for the function simplexml_load_string
its too good…. 😀