How To Convert XML To Associative Array in PHP

Today I need to convert XML file into associative array to store in variable. So I have done a lot of googling and I have 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,

In Below tutorial I will let you know how to convert XMl into array in php.

I have sample.xml config xml file

Select Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<h3>Step 1: XML File</h3>
<?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 File Into String

Now I will use file_get_contents() PHP method to read entire file into a string.

Select Code
1
$xmlfile = file_get_contents($path);
Result

convert xml into string

Step 3: Convert string of XML into an Object

Right now I have xml file as an string so I need to convert this xml string into Objects,So I will use simplexml_load_string() method to convert string of XML into an object.

Select Code
1
$ob= simplexml_load_string($xmlfile);
Result

convert xml into objects

Step 4: Encode XML Object Into JSON

Now I will encode XML object into JSON, below code will convert xml object into json string.

Select Code
1
$json  = json_encode($ob);
Result

Json encode

Step 5: Decode Json Object

Finally we will decode json to get array from json string.

Select Code
1
$configData = json_decode($json, true);
Result

convert xml into array

Full Source Code

Select Code
1
2
3
4
$xmlfile = file_get_contents($path);
		$ob= simplexml_load_string($xmlfile);
		$json  = json_encode($ob);
		$configData = json_decode($json, true);