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:

function xml_encode_products( $products ) {
	$w=new XMLWriter();
	foreach($products as $prod) {
		foreach($prod as $key=>$value) {
	return $w->outputMemory(true);

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

    array('name' => 'Turntable',
          'price' => '80.00', 

    array('name' => 'Guitar',
          'price' => '400.00', 

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


The resulting xml (whitespace added for readability):

<?xml version="1.0" encoding="UTF-8"?>