Convert Array to XML and XML to Array in PHP


XML (Extensible Markup Language) is a markup language that encodes documents in a machine-readable and human-readable format. Generally, XML is used to store and transport data.

You can use XML many ways in the web application. If you’re concerned about database size and want to reduce database uses, XML can help you to free the space from the database. Instead of the database you can store the data in the XML file and retrieve data from XML file without connecting to the database.

In this tutorial, we will show you how to convert PHP associative or multidimensional array to XML and stored in the XML file. Also, the example code shows how to parse the XML file and convert XML data to array in PHP.

Convert PHP Multidimensional Array to XML File

createXML() Function:
For better usability, all the Array to XML conversion code will be grouped together in a PHP function. The createXML() function converts PHP multidimensional array to XML file. The data array needs to be passed as a parameter in createXML() function. The createXML() function create an XML document using DOMDocument class and insert the PHP array content in this XML document. At the end, the XML document is saved as an XML file in the specified file path.

function createXML($data) {
    
$title $data['title'];
    
$rowCount count($data['users']);
    
    
//create the xml document
    
$xmlDoc = new DOMDocument();
    
    
$root $xmlDoc->appendChild($xmlDoc->createElement("user_info"));
    
$root->appendChild($xmlDoc->createElement("title",$title));
    
$root->appendChild($xmlDoc->createElement("totalRows",$rowCount));
    
$tabUsers $root->appendChild($xmlDoc->createElement('rows'));
    
    foreach(
$data['users'] as $user){
        if(!empty(
$user)){
            
$tabUser $tabUsers->appendChild($xmlDoc->createElement('user'));
            foreach(
$user as $key=>$val){
                
$tabUser->appendChild($xmlDoc->createElement($key$val));
            }
        }
    }
    
    
header("Content-Type: text/plain");
    
    
//make the output pretty
    
$xmlDoc->formatOutput true;
    
    
//save xml file
    
$file_name str_replace(' ''_',$title).'_'.time().'.xml';
    
$xmlDoc->save("files/" $file_name);
    
    
//return xml file name
    
return $file_name;
}

PHP Multidimensional Array
The following multidimensional array will save as XML file using PHP

$data = array(
    
'title' => 'Users Information',
    
'users' => array(
        array(
'name' => 'John Doe''email' => 'john@doe.com'),
        array(
'name' => 'Merry Moe''email' => 'merry@moe.com'),
        array(
'name' => 'Hellary Riss''email' => 'hellary@riss.com')
    )
);

PHP Array to XML File Conversion
You only need to use createXML() function and pass data array in it to convert array to XML in PHP.

echo createXML($data);

The example code will create the following XML document.

<?xml version="1.0"?>
<user_info>
  <title>Users Information</title>
  <totalRows>3</totalRows>
  <rows>
    <user>
      <name>John Doe</name>
      <email>john@doe.com</email>
    </user>
    <user>
      <name>Merry Moe</name>
      <email>merry@moe.com</email>
    </user>
    <user>
      <name>Hellary Riss</name>
      <email>hellary@riss.com</email>
    </user>
  </rows>
</user_info>

Convert XML to PHP Associative Array

Now we will read the XML data from file and convert the XML to array using PHP.

  • Read entire file into string using file_get_contents() function in PHP.
  • Convert XML string into an object using simplexml_load_string() function in PHP.
  • Convert object into JSON using json_encode() function.
  • Convert JSON data into associative array using json_decode() function.
//xml file path
$path "files/path-to-document.xml";

//read entire file into string
$xmlfile file_get_contents($path);

//convert xml string into an object
$xml simplexml_load_string($xmlfile);

//convert into json
$json  json_encode($xml);

//convert into associative array
$xmlArr json_decode($jsontrue);
print_r($xmlArr);

The example code will convert the XML file to the following associative array.

Array
(
    [title] => Users Information
    [totalRows] => 3
    [rows] => Array
        (
            [user] => Array
                (
                    [0] => Array
                        (
                            [name] => John Doe
                            [email] => john@doe.com
                        )

                    [1] => Array
                        (
                            [name] => Merry Moe
                            [email] => merry@moe.com
                        )

                    [2] => Array
                        (
                            [name] => Hellary Riss
                            [email] => hellary@riss.com
                        )

                )

        )

)

Are you want to get implementation help, or modify or extend the functionality of this script? Submit paid service request

Recommended Tutorials For You

Leave a reply