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
- Qwen2.5-Coder-32B is an LLM that can code well that runs on my Mac - 12th November 2024
- Visualizing local election results with Datasette, Observable and MapLibre GL - 9th November 2024
- Project: VERDAD - tracking misinformation in radio broadcasts using Gemini 1.5 - 7th November 2024