Convert Array to XML and XML to Array in PHP

Convert Array to XML and XML to Array in PHP

The XML (Extensible Markup Language) is a markup language that encodes documents in a machine-readable and human-readable format. Usually, you can use Extensible Markup Language to store and transport data.

You can use XML in several ways in a web application. Therefore, if you are worried about database size and want to lessen database usage, XML can support you free up space from the database. As an alternative to a database, you can store data in an XML file and retrieve data from an XML file without connecting to the database. With the help of this tutorial, we will explain to you how to convert PHP associative or multidimensional array to XML and store it in the XML file. Also, the sample code shows how to parse the XML file and convert XML data to an array in PHP.

SEE ALSO: Convert HTML to PDF using JavaScript

Convert PHP Multidimensional Array to XML File

createXML() Function:

To use it in a better way, group together all arrays of XML conversion code in a PHP function. The CreateXML () function converts the PHP multidimensional array into an XML file. The data array needs to be passed as a parameter to the createXML () function. The CreateXML () function creates an XML document using the DOMDocument class and inserts PHP array contents into this XML document. Finally, 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;
}

SEE ALSO: Convert HTML to MS Word Document using PHP

PHP Multidimensional Array

By using PHP we can save the following multidimensional array as XML file.

$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 createXML()  function and pass data array in it to convert array to XML in PHP.

echo createXML($data);

The example code will make 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 the file and convert the XML to an array using PHP.

//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($json, true);
print_r($xmlArr);

The example code will convert the XML file to the following 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
                        )

                )

        )

)

Also, read our previous article- Live Image Upload, Crop and Resize using jQuery and PHP

Exit mobile version