how to: Generating XML from PHP
August 15, 08 by Gabi SolomonI had to do a small REST application on a project recently and i wanted to find a small easy way of returning the response in XML.
After a little searching find this rather old post ( but just what i was looking for ) on Simon Willison’s Weblog. It featured a small php class to generate XML.
Example Code
-
);
-
$xml = new XmlWriter();
-
$xml->push('zoo');
-
foreach ($array as $animal) {
-
$xml->element('name', $animal[2]);
-
$xml->element('food', $animal[1]);
-
$xml->pop();
-
}
-
$xml->pop();
XML returned
-
<?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>
Attention
A little heads up, if your running php you might encounter this error:
Fatal error: Cannot redeclare class xmlwriter in /var/www/web4/cgi-bin/includes/XmlWriter.class.inc on line 6
Thats because php already has a built in php class called xmlwriter, to fix it all you need to do is rename it.
hope this helps somebody.
Cheers

