Convert associative arrays into XML in PHP

Written by pelister. Posted in PHP

PHP has introduced a lot of new functions and classes with version 5. XMLWriter class is one of the new feature which can be used to write xml documents with PHP. Though there are tons of classes and functions to write xml format, XMLWriter class is poorly documented and doesn’t have too many  examples. write xml with phpXML is widely used format next to JSON for most of the web based APIs. In this simple article let us touch the basics of PHP XMLWriter with a sample code. We will convert an associative array into XML document.

This is our array.

<?php

$stat['clicks'] = 10;
$stat['platform'] = array( 'windows' => 4 , 'linux' => 6 );
$stat['browser'] = array( 'Firefox' => 3 , 'Chrome' => 7 );

Now let us use the PHP XML writer class, first create an instance of XML class and that instance (object) will be used to access all the methods within the class to write our XML document.

$xml = new XmlWriter();
$xml->openMemory();
$xml->startDocument( '1.0', 'utf-8' );
$xml->startElement( 'stats') ;

write_xml( $xml, $stat );

$xml->endElement();
echo $xml->outputMemory( true )

– then we use openMemory() method as we are going to write it to the buffer and not to the filesystem, in case if you like to write the xml document to a local file system you can use the method openURI( uri string )

– then we call startDocument() with xml version and type of encoding as parameters.

startElement() writes the starting element tag

– then we call our user defined function write_xml() which takes xml object and the array as parameters

Here is our write_xml function

function write_xml( XMLWriter $xml, $data ) {
    foreach( $data as $key => $value ) {
        if( is_array( $value )) {
            $xml->startElement( $key );
            write_xml( $xml, $value );
            $xml->endElement( );
            continue;
        }
        $xml->writeElement( $key, $value );
    }
}

The above function recursively parses the array and converts it into xml using the startElement() and endElement() methods of xml class and finally we output the memory.

Sample output of the above code

<?xml version="1.0" encoding="UTF-8"?>
<stats>
  <clicks> 10 </clicks>
  <platform>
    <windows> 4 </windows>
    <linux> 6 </linux>
  </platform>
  <browser>
      <Firefox> 3 </Firefox>
      <Chrome> 7 </Chrome>
  </browser>
</stats>

Happy Coding…

1 Star2 Stars3 Stars4 Stars5 Stars (6 votes, average: 4.83 out of 5)
Loading...
pelister
3D modeler and Web designer. Founder of Techlister. Love to build sites using WordPress and Joomla. Interested in Astronomy, project member of SETI (Search for Extra Terrestrial Intelligence).

Tags: , , , ,

Comments (1)

  • shiva

    |

    Useful article for beginners in XML

    Reply

Leave a comment

Techlister© - 2012