How To Convert XML To Associative Array in PHP

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,

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);
Result:
convert xml into string

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);
Result:
convert xml into objects

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);
Result:
Json encode

Step 5: Decode Json Object
Finally, We will decode JSON to get an array from JSON string.

$configData = json_decode($json, true);
Result:
convert xml into array

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

5 thoughts on “How To Convert XML To Associative Array in PHP

Leave a Reply

Your email address will not be published.