Array to XML Conversion and XML to Array Convert in PHP

Many times we need to store the data in XML format into the database or into the file. In this article, we are going to discuss how we can convert array to XML and XML to array in PHP.

Nowadays we mainly use JSON format to store and send the data from one location to another. But what if we require to store or send the data in XML format.

Let’s suppose we have to work with the third party database and to communicate to that database we have only XML API available there, then obviously we need to fetch those XML API and need to convert them in PHP array to work around. And the same thing applies when you need to provide some data using API to a third party when demands the API in XML format. In this article, we will learn how we can convert PHP simple array, associative array, or multidimensions array to XML format and vice versa.

If you are concerned about the size of the database, XML can help us to free some space from the database. You can use an XML file to save the data instead of saving data into the database you can save data in XML files and later when required you can get the data in an array using to XML to PHP conversion method that we have explained below.

What is XML

XML stands for an extensible markup language. A markup language is a set of codes, or tags, that describes the text in a digital document. XML is a software- and hardware-independent tool for storing and transporting data.

  • XML stands for extensible Markup Language
  • XML is a markup language much like HTML
  • XML was designed to store and transport data
  • XML was designed to be self-descriptive
  • XML is a W3C Recommendation

The Difference Between XML and HTML

XML and HTML were designed with different goals:

  • XML was designed to carry data – with a focus on what data is
  • HTML was designed to display data – with a focus on how data looks
  • XML tags are not predefined like HTML tags are

Convert PHP Multidimensional Array to the XML file format

$array = array(
    'class'=> 'class 10th',
    'student'=> array(
      '0' => array(
        'name' 		=> 'David',
        'rollNo'		=> '34'
      ),
      '1' => array(
        'name' 		=> 'Sunny',
        'rollNo'		=> '30'
      ),
      '2' => array(
        'name' 		=> 'Illa',
        'rollNo'		=> '37'
      ),
      '3' => array(
        'name' 		=> 'Monna',
        'rollNo'		=> '35'
      )
    )
  );

Method for generating XML

Now, you need to create a function generatXML()

function generateXML($data) {
    $title = $data['class'];
    $rowCount = count($data['student']);
    
    //create the xml document
    $xmlDoc = new DOMDocument();
    
    $root = $xmlDoc->appendChild($xmlDoc->createElement("student_info"));
    $root->appendChild($xmlDoc->createElement("title",$title));
    $root->appendChild($xmlDoc->createElement("totalRows",$rowCount));
    $tabUsers = $root->appendChild($xmlDoc->createElement('rows'));
    
    foreach($data['student'] as $user){
        if(!empty($user)){
            $tabUser = $tabUsers->appendChild($xmlDoc->createElement('student'));
            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 the data array in it to convert the array to XML in PHP. This function creates an XML document using DOMDocument class and inserts the PHP array content in this XML document. at the end, XML file saved as in specified location with given file name.

Array to XML Complete code

<?php


function generateXML($data) {
    $title = $data['class'];
    $rowCount = count($data['student']);
    
    //create the xml document
    $xmlDoc = new DOMDocument();
    
    $root = $xmlDoc->appendChild($xmlDoc->createElement("student_info"));
    $root->appendChild($xmlDoc->createElement("title",$title));
    $root->appendChild($xmlDoc->createElement("totalRows",$rowCount));
    $tabUsers = $root->appendChild($xmlDoc->createElement('rows'));
    
    foreach($data['student'] as $user){
        if(!empty($user)){
            $tabUser = $tabUsers->appendChild($xmlDoc->createElement('student'));
            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;
}


// array 
$array = array(
    'class'=> 'class 10th',
    'student'=> array(
      '0' => array(
        'name' 		=> 'David',
        'rollNo'		=> '34'
      ),
      '1' => array(
        'name' 		=> 'Sunny',
        'rollNo'		=> '30'
      ),
      '2' => array(
        'name' 		=> 'Illa',
        'rollNo'		=> '37'
      ),
      '3' => array(
        'name' 		=> 'Monna',
        'rollNo'		=> '35'
      )
    )
  );

  generateXML($array);
?>

Output:

<?xml version="1.0"?>
<student_info>
  <title>class 10th</title>
  <totalRows>4</totalRows>
  <rows>
    <student>
      <name>David</name>
      <rollNo>34</rollNo>
    </student>
    <student>
      <name>Sunny</name>
      <rollNo>30</rollNo>
    </student>
    <student>
      <name>Illa</name>
      <rollNo>37</rollNo>
    </student>
    <student>
      <name>Monna</name>
      <rollNo>35</rollNo>
    </student>
  </rows>
</student_info>

Convert XML to PHP Associative Array

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

  • We will read the XML data from the file using file_get_contents() and convert the XML to an array using PHP.
  • Convert XML string into an object using simplexml_load_string() function in PHP.
  • Then incode the putput to JSON using json_encode() function.
  • Convert JSON data into array using json_decode() function.

<?php

function xml_to_array(){
    //xml file path
    $path = "class_10th.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);
}
xml_to_array();
?>

Output:

Array
(
    [title] => class 10th
    [totalRows] => 4
    [rows] => Array
        (
            [student] => Array
                (
                    [0] => Array
                        (
                            [name] => David
                            [rollNo] => 34
                        )

                    [1] => Array
                        (
                            [name] => Sunny
                            [rollNo] => 30
                        )

                    [2] => Array
                        (
                            [name] => Illa
                            [rollNo] => 37
                        )

                    [3] => Array
                        (
                            [name] => Monna
                            [rollNo] => 35
                        )

                )

        )

)

Conclusion:

We have tried to explain the above code with possible example, hope you liked the article. You can also visit How to check an array is multidimensional or not in PHP to check if array in multidimensional or not before using it in XML conversion.