Convert multidimensional array to XML file in PHP

XML stands for eXtensible Markup Language. XML is a markup language that encodes documents in a machine-readable and human-readable format. XML was designed to store and transport data. XML is often used for distributing data over the Internet. You can use XML in 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. A website sitemap is also generated in XML format.

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

I have a two-dimensional input array containing the array of key/element pairs. For better understanding, all the Array to XML conversion codes will be grouped together in a PHP function. The generateXML() function converts PHP multidimensional array to XML file format. The data array needs to be passed as a parameter in generateXML() function.

This function creates an XML document using the DOMDocument class and inserts the PHP array content in this XML document. In the end, the XML document is saved as an XML file in the specified file location with a given file name.

 

First of all, Create PHP Multidimensional Array for converting to the XML file format:

$array = array(
		'department'=> 'Accounts',
		'employe'=> array(
			'0' => array(
				'name' 		=> 'Iron Man',
				'age'		=> '34'
			),
			'1' => array(
				'name' 		=> 'Black',
				'age'		=> '30'
			),
			'2' => array(
				'name' 		=> 'Captain',
				'age'		=> '37'
			),
			'3' => array(
				'name' 		=> 'Loki',
				'age'		=> '35'
			)
		)
	);

 

Now, you need to create a function generatXML() :

function generateXML($data) {
    $title = $data['department'];
    $rowCount = count($data['employe']);
    
    //create the xml document
    $xmlDoc = new DOMDocument();
    
    $root = $xmlDoc->appendChild($xmlDoc->createElement("employe_info"));
    $root->appendChild($xmlDoc->createElement("title",$title));
    $root->appendChild($xmlDoc->createElement("totalRows",$rowCount));
    $tabUsers = $root->appendChild($xmlDoc->createElement('rows'));
    
    foreach($data['employe'] as $user){
        if(!empty($user)){
            $tabUser = $tabUsers->appendChild($xmlDoc->createElement('employe'));
            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).'.xml';
    $xmlDoc->save($file_name);
    
    //return xml file name
    return $file_name;
}

 

You only need to use generateXML() function and pass data array in it to convert array to XML in PHP.

generateXML($array);

 

The example code will create your Multidimensional Array into the following XML document with your given file name.

<employe_info>
<title>Accounts</title>
<totalRows>4</totalRows>
<rows>
<employe>
<name>Iron Man</name>
<age>34</age>
</employe>
<employe>
<name>Black</name>
<age>30</age>
</employe>
<employe>
<name>Captain</name>
<age>37</age>
</employe>
<employe>
<name>Loki</name>
<age>35</age>
</employe>
</rows>
</employe_info>

 

Convert XML to PHP Associative Array

For converting XML to PHP Associative Array we will use the few following steps.

  1. We will read the XML data from file and convert the XML to an array using PHP.
  2. Read entire file into string using file_get_contents() function in PHP.
  3. Convert XML string into an object using simplexml_load_string() function in PHP.
  4. Convert object into JSON using json_encode() function.
  5. Convert JSON data into associative array using json_decode() function.

For better way, we will create an xml_to_array() function with all these given steps:

function xml_to_array(){
    //xml file path
    $path = "Accounts.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
    $array_data = json_decode($json, true);
    
    print_r($array_data);
}

 

Now, simply call this function to convert XML to Multidimensional Array:

xml_to_array();

 

The output of this function will be like this:

arry(
    [title] => Accounts
    [totalRows] => 4
    [rows] => Array
        (
            [employe] => Array
                (
                    [0] => Array
                        (
                            [name] => Iron Man
                            [age] => 34
                        )

                    [1] => Array
                        (
                            [name] => Black
                            [age] => 30
                        )

                    [2] => Array
                        (
                            [name] => Captain
                            [age] => 37
                        )

                    [3] => Array
                        (
                            [name] => Loki
                            [age] => 35
                        )

                )

        )

)

 

Final code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<?php
function generateXML($data) {
    $title = $data['department'];
    $rowCount = count($data['employe']);
    
    //create the xml document
    $xmlDoc = new DOMDocument();
    
    $root = $xmlDoc->appendChild($xmlDoc->createElement("employe_info"));
    $root->appendChild($xmlDoc->createElement("title",$title));
    $root->appendChild($xmlDoc->createElement("totalRows",$rowCount));
    $tabUsers = $root->appendChild($xmlDoc->createElement('rows'));
    
    foreach($data['employe'] as $user){
        if(!empty($user)){
            $tabUser = $tabUsers->appendChild($xmlDoc->createElement('employe'));
            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).'.xml';
    $xmlDoc->save($file_name);
    
    //return xml file name
    return $file_name;
}

function xml_to_array(){
    //xml file path
    $path = "Accounts.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
    $array_data = json_decode($json, true);
    
    print_r($array_data);
}
?>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Multidimensional Array To XML and XML to Array</title>
</head>
<body>
<div class="container">
  <h2 class="text-success">Multidimensional Array To XML and XML to Array</h2>
    <?php
    $array = array(
		'department'=> 'Accounts',
		'employe'=> array(
			'0' => array(
				'name' 		=> 'Iron Man',
				'age'		=> '34'
			),
			'1' => array(
				'name' 		=> 'Black',
				'age'		=> '30'
			),
			'2' => array(
				'name' 		=> 'Captain',
				'age'		=> '37'
			),
			'3' => array(
				'name' 		=> 'Loki',
				'age'		=> '35'
			)
		)
	);
    generateXML($array);
    
    echo "XML to Array: <br>";
    xml_to_array();
    ?>
</div>
   
</body>
</html>

Did you find this page helpful? X

Comments

Ravindra

i was searching for array To XML, but there is both multidimensional array to XML and XML to array.. thank you for writing this...