Codementor Events

Convert multidimensional array to XML file in PHP

Published Jul 12, 2019
Convert multidimensional array to XML file in PHP

XML stands for eXtensible Markup Language. In this post you’ll lean about convert multidimensional array to XML. This 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 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. Website sitemap are also generate in XML format.

In this tutorial, we will show you how to convert PHP multidimensional or associative array to the 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 code 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 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 the given file name.

Muyltidimentnal Array

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

Method for generating XML

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 the 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.Object to JSON convert 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);
}

Simply call this function to convert XML to Multidimensional Array

xml_to_array();

Output

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 for Convert multidimensional array to XML

<!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>
Discover and read more posts from Amit Pandey (Coding Issue)
get started
post commentsBe the first to share your opinion
Show more replies