Array to XML Conversion using PHP

Last modified on January 30th, 2018 by Vincy.

When there is a necessity to serialize a PHP array, it can be converted to XML, store and also may be transmitted. In that process, the key/element pairs are converted into structural nodes. The XML nodes are created in the name of the keys and the array element is added as the child to this key nodes.

I have a two-dimensional input array containing the array of key/element pairs. The inner array elements hold the title, link and the description of the article. While converting this array to an XML document, I created a root node called items. Then, I iterated the input array and created child item with the title, link and description nodes on each iteration.


PHP Code to Convert Array to XML

This code has the input array structure supplied to the PHP foreach loop to iterate the inner array elements. Before iterating the input array, I have created an object for the DOMDocument() class. This object is used to create the XML document.

I created the <items> element and appended it to the XML document with the reference of the DOMDocument object. Then, the input array is iterated to get the title, link and the description data for each iteration. XML nodes <title>, <link> and <description> is created for each item to store the array data and the nodes are added to the XML document.

After converting PHP array to an XML document, I saved it as a file in the specified target. This file will be downloaded to the user’s browser and removed permanently from the target folder.

$input_array = array(
    'article' => array(
            'title' => 'Favorite Star Rating with jQuery',
            'link' => '',
            'description' => 'Doing favorite star rating using jQuery Displays HTML stars.'
            'title' => 'PHP RSS Feed Read and List',
            'link' => '',
            'description' => 'simplexml_load_file() function is used for reading data from XML.'

$xml = new DOMDocument();

$rootNode = $xml->appendChild($xml->createElement("items"));

foreach ($input_array['article'] as $article) {
    if (! empty($article)) {
        $itemNode = $rootNode->appendChild($xml->createElement('item'));
        foreach ($article as $k => $v) {
            $itemNode->appendChild($xml->createElement($k, $v));

$xml->formatOutput = true;

$backup_file_name = 'file_backup_' . time() . '.xml';

header('Content-Description: File Transfer');
header('Content-Type: application/xml');
header('Content-Disposition: attachment; filename=' . basename($backup_file_name));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($backup_file_name));
exec('rm ' . $backup_file_name);


This PHP code tutorial was published on January 30, 2018.

↑ Back to Top

Share this Article