Simon Willison’s Weblog

Subscribe

XmlWriter: Generating XML from PHP

29th April 2003

Lars Marius Garshol’s XMLWriter class for Python struck me as a particularly elegant solution for generating simple XML documents without having to worry about encoding issues, missing tags and so forth—so I re-implemented it in PHP:

XmlWriter.class.php

Example code:

$array = array(
    array('monkey', 'banana', 'Jim'),
    array('hamster', 'apples', 'Kola'),
    array('turtle', 'beans', 'Berty'),
);
$xml = new XmlWriter();
$xml->push('zoo');
foreach ($array as $animal) {
    $xml->push('animal', array('species' => $animal[0]));
    $xml->element('name', $animal[2]);
    $xml->element('food', $animal[1]);
    $xml->pop();
}
$xml->pop();
print $xml->getXml();

Which produces this:

<?xml version="1.0" encoding="utf-8"?>
<zoo>
  <animal species="monkey">
    <name>Jim</name>
    <food>banana</food>
  </animal>
  <animal species="hamster">
    <name>Kola</name>
    <food>apples</food>
  </animal>
  <animal species="turtle">
    <name>Berty</name>
    <food>beans</food>
  </animal>
</zoo>

This is XmlWriter: Generating XML from PHP by Simon Willison, posted on 29th April 2003.

Next: In praise of functional programming

Previous: Skill Swap

Previously hosted at http://simon.incutio.com/archive/2003/04/29/xmlWriter