Today, I need to convert the XML file into an associative array to store in variables. So I have done a lot of googling and found several methods/views and libraries to convert XML objects into Array, but in stack overflow – I have found below a simple script to convert XML into an 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 an array in PHP.
Step 1: Sample XML file
I have created the below xml sample.xml file, which will use to convert into an array using PHP.
<?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.
$xmlfile = file_get_contents($path);
Step 3: Convert a string of XML into an Object,
We have an XML file as a string, So Let’s convert this XML string into Objects. I will use simplexml_load_string() php method to convert a string of XML into an object.
$ob= simplexml_load_string($xmlfile);
Step 4: Encode XML Object Into JSON
I will encode the XML object into JSON, the below code will convert XML object into JSON string.
$json = json_encode($ob);
Step 5: Decode Json Object
Finally, We will decode JSON to get an array from JSON string.
$configData = json_decode($json, true);
Full Source Code
$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…. 😀