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.
In Below tutorial I will tell you how its converted step by step.
I have Facebook.xml config xml file:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
<h6>Step 1: XML File</h6>
<?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 file_get_contents PHP method to Reads entire file into a string.
1
$xmlfile = file_get_contents($path);
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.
1
$ob= simplexml_load_string($xmlfile);
Step 4: Encode XML Object Into Json
Now I will encode XML object into json.Below code is converting xml object into json string.
1
$json = json_encode($ob);
Step 5:Decode Json Object
Fnally we will decode json decode to get array from json string.
1
$configData = json_decode($json, true);
Full Code
1 2 3 4 5 6 7
$xmlfile = file_get_contents($path); $ob= simplexml_load_string($xmlfile); $json = json_encode($ob); $configData = json_decode($json, true);


