Simon Willison’s Weblog

XmlWriter: Generating XML from PHP

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:


Example code:

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

Which produces this:

<?xml version="1.0" encoding="utf-8"?>
  <animal species="monkey">
  <animal species="hamster">
  <animal species="turtle">

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