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:
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>
More recent articles
- Hacking the WiFi-enabled color screen GitHub Universe conference badge - 28th October 2025
- Video: Building a tool to copy-paste share terminal sessions using Claude Code for web - 23rd October 2025
- Dane Stuckey (OpenAI CISO) on prompt injection risks for ChatGPT Atlas - 22nd October 2025