How to Convert Multidimensional Array to XML File in PHP

Hi, today we’ll see how to convert multidimensional array to xml file in php. XML, the EXtensible Markup Language is a good old data-exchange format and lost its popularity to JSON. But the sad truth is XML still exists and used to store and exchange data on the WEB. If you are one among the developers who has to deal with XML, then this tutorial is aimed at you. Converting an associative array or a complex multi-dimensional array no matter what, the php script I have given here will easily convert those arrays to xml file.

Converting PHP Multi-Dimensional Array to XML File

Here’s the breakdown of the steps we are going to implement for php array to xml conversion.

Step-1: Create a function array2XML() to convert array to xml: This function will continuously iterates through the given multi-dimensional array and add each (key, value) pairs as a separate xml node with the help of php’s SIMPLEXML class.

Step-2: Next define the php associative or multi-dimensional array to convert.

Step-3: Create a new instance of the simplexml class.

Step-4: Callback to the function array2XML() to convert the array (defined in step-2) to an xml object.

Step-5: Finally save the generated xml as a file.

PHP Code for Array to XML Conversion

<?php
// function to convert multi-dimensional array to xml
function array2XML($obj, $array)
{
    foreach ($array as $key => $value)
    {
        if(is_numeric($key))
            $key = 'item' . $key;

        if (is_array($value))
        {
            $node = $obj->addChild($key);
            array2XML($node, $value);
        }
        else
        {
            $obj->addChild($key, htmlspecialchars($value));
        }
    }
}

// define php multi-dimensional array
$my_array = array (
    '0' => array (
        'id' => 'XYZ100',
        'personal' => array (
            'name' =>'Ashton Cox',
            'gender' => 'Male',
            'age' => 32,
            'address' => array (
                 'street' => '7 24th Street',
                 'city' => 'New York',
                 'state' => 'NY',
                 'zipcode' => '10038'
             )
        ),
        'profile' => array (
            'position' => 'Team Lead',
            'department' => 'Software'
        )
    ),
    '1' => array (
        'id' => 'XYZ121',
        'personal' => array (
            'name' => 'Rhona Davidson',
            'gender' => 'Female',
            'age' => 40,
            'address' => array (
                 'street' => 'S2 115th Street',
                 'city' => 'New York',
                 'state' => 'NY',
                 'zipcode' => '10100'
             )
        ),
        'profile' => array (
            'position' => 'Integration Specialist',
            'department' => 'Operations'
        )
    )
);

// create new instance of simplexml
$xml = new SimpleXMLElement('<root/>');

// function callback
array2XML($xml, $my_array);

// save as xml file
echo (($xml->asXML('data.xml')) ? 'Your XML file has been generated successfully!' : 'Error generating XML file!');
?>

As you can see the array2XML() is a recursive function that pretty much parse through arrays of several depths. This will also work with associative arrays with numeric keys and store them as <item0>, <item1> as xml don’t allow numeric keyed nodes like <0>, <1>, <2>, ... and consider them as invalid.

The method addChild() will add an xml node to the object.

The statement new SimpleXMLElement('<root/>'); will create an xml object with the top node as <root></root>.

The line $xml->asXML('data.xml') will save the xml string to ‘data.xml’ file. Make sure to provide complete file path to save the file in different location.

Now run the above script and the xml file will be generated without any errors.

Here’s the xml file generated by the above php script.

<?xml version="1.0" ?> 
- <root>
    - <item0>
          <id>XYZ100</id> 
        - <personal>
              <name>Ashton Cox</name> 
              <gender>Male</gender> 
              <age>32</age> 
            - <address>
                  <street>7 24th Street</street> 
                  <city>New York</city> 
                  <state>NY</state> 
                  <zipcode>10038</zipcode> 
              </address>
          </personal>
        - <profile>
              <position>Team Lead</position> 
              <department>Software</department> 
          </profile>
      </item0>
    - <item1>
          <id>XYZ121</id> 
        - <personal>
              <name>Rhona Davidson</name> 
              <gender>Female</gender> 
              <age>40</age> 
            - <address>
                  <street>S2 115th Street</street> 
                  <city>New York</city> 
                  <state>NY</state> 
                  <zipcode>10100</zipcode> 
              </address>
          </personal>
        - <profile>
              <position>Integration Specialist</position> 
              <department>Operations</department> 
          </profile>
      </item1>
  </root>

Inserting XML String into Database

Wan’t to store xml data as a string in database? Then use this below code instead of the last statement in the php script.

$data = $xml->asXML();

Now the variable $data contains the array in the xml format and you can easily insert into database like you do normally.

Read Also:

And that was all about converting multi-dimensional array to xml in php. Alternatively if you want the reverse process, check this tutorial to Covert XML File to Array in PHP.

5 comments:

  1. Really. You made life easy :P

    ReplyDelete
  2. Nice Tutorial , I have one question , instead of saving in xml file , how can we just show this on a page as XML format

    ReplyDelete