XMLWriter in PHP

Posted by: gbluma

Tagged in: XML , Programming , PHP

Every now and then I find myself needing to export a set of objects to XML. I usually find a quick way to write a dumb function to do it, but this is usually not the most elegant solution and rarely does it scale up to handle more complex data structures. The other option is to serialize the data into xml, but usually these methods suffer from a large performance overhead and should only be used if you can tweak the serializer to work only the right pieces of data.

I have since added XMLWriter to my toolset. Which, oddly enough, is built right into PHP (as of version 5.1.2) and based on the widely popular libxml engine. I find it to be very quick, both in performance and in ease of programming. Best of all, the code makes more sense than any of any of my own homemade tools.

Here's an example where demonstrate how to export a list of products to xml:

<?php
function xml_encode_products( $products ) {
	$w=new XMLWriter();
	$w->openMemory();
	$w->startDocument('1.0','UTF-8');
	$w->startElement("products");
	foreach($products as $prod) {
		$w->startElement("product");
		
		foreach($prod as $key=>$value) {
			$w->startElement($key);
		    	$w->text($value);
		    $w->endElement();
		}
				    
		$w->endElement();
	}
	$w->endElement();
	return $w->outputMemory(true);
}

$data = array( 
    array('name' => 'iPod',
          'price' => '99.99', 
          'color' => 'silver', 
          'used'  => 'no'),

    array('name' => 'Turntable',
          'price' => '80.00', 
          'color'=>'black', 
          'used'=>'yes'),

    array('name' => 'Guitar',
          'price' => '400.00', 
          'color'=>'sunburst', 
          'used'=>'yes')
);

header("Content-Type: application/xml");
echo xml_encode_products( $data );

?>

The resulting xml (whitespace added for readability):

<?xml version="1.0" encoding="UTF-8"?>
<products>
    <product>
        <name>iPod</name>
        <price>99.99</price>
        <color>silver</color>
        <used>no</used>
    </product>
    <product>
        <name>Turntable</name>
        <price>80.00</price>
        <color>black</color>
        <used>yes</used>
    </product>
    <product>
        <name>Guitar</name>
        <price>400.00</price>
        <color>sunburst</color>
        <used>yes</used>
    </product>
</products>