How to convert XML file into array in PHP?


To convert the XML document into PHP array, we have to utilize some PHP functions. The procedure is explained underneath with an example.

Step 1:

We have to create an XML file that needs to convert into the array.

abc.xml
<?xml version='1.0'?>
<userdb>
<firstname name='Alex'>
<symbol>AL</symbol>
<code>A</code>
</firstname>
<firstname name='Sandra'>
<symbol>SA</symbol>
<code>S</code>
</firstname>
</userdb>


Step 2:

The above XML file will import into PHP using file_get_contents() function which read the entire file as a string and stores into a variable.

Step 3:

After the above step, we can easily convert the string into an object through the inbuilt functions simplexml_load_string() of PHP.

Step 4:

After the above step, we can use json_encode() function to present the object in the json encoded string.

Step 5:

The json_decode() function decode a JSON string. It converts a JSON encoded string into a PHP array.

Example:

<?php
// xml file path
   $path = "abc.xml";
   $xmlfile = file_get_contents($path);
   $new = simplexml_load_string($xmlfile);
   $jsonfile = json_encode($new);
   $myarray = json_decode($jsonfile, true);
   print_r($myarray);
?>
raja
Published on 25-Jun-2019 14:18:46
Advertisements