how to get values from xml object array in php?

In this tutorial php xml to array, 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.

  • using file_get_contents
  • using simplexml_load_string
  • using json_encode
  • using json_decode

<?xml version='1.0'?>  
<moleculedb>  
    <molecule name='Tamilrokers'>  
        <symbol>tamil</symbol>  
        <code>T</code>  
    </molecule>  
    <molecule name='Jiorokers'>  
        <symbol>jio</symbol>  
        <code>J</code>  
    </molecule>
	<molecule name='MyMaths'>  
        <symbol>math</symbol>  
        <code>M</code>  
    </molecule>
</moleculedb>

Step 2: Convert sample.xml File Into String

Now, I will use simply file_get_contents() PHP in-built method to read entire file into a string and store into $productinfofile variable.

Read Also:  left outer join vs left join

$productinfofile = 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 in-built method to convert string of XML into an object.

$ob= simplexml_load_string($productinfofile);

Step 4: Encode XML Object Into JSON

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

Read Also:  how to delete Multiple Selected rows using checkbox in laravel

$json  = json_encode($ob);

Result

Step 5: Decode Json Object

last step, I will decode json to get array from json string.

$allShopDetails = json_decode($json, true);

Full Source Code

$path = "sample.xml"
$productinfofile = file_get_contents($path);
$ob= simplexml_load_string($productinfofile);
$json  = json_encode($ob);
$allShopDetails = json_decode($json, true);
echo "<pre>":print_r($allShopDetails);