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
tamil T
jio J
math M
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.
$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.
$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);