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'?>  
    <molecule name='Tamilrokers'>  
    <molecule name='Jiorokers'>  
	<molecule name='MyMaths'>  

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.

Also Read This πŸ‘‰   PHP Contact Form Send Email File Attachment Example

$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.

Also Read This πŸ‘‰   How to Convert XML to JSON in PHP?

$json  = json_encode($ob);


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