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…

Convert associative arrays into XML in PHP

Leave a Reply

Your email address will not be published. Required fields are marked *