Spiga

how to: Generating XML from PHP

August 15, 08 by Gabi Solomon

I 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

PHP:
  1. $array = array(
  2.     array('monkey', 'banana', 'Jim'),
  3.     array('hamster', 'apples', 'Kola'),
  4.     array('turtle', 'beans', 'Berty'),
  5. );
  6. $xml = new XmlWriter();
  7. $xml->push('zoo');
  8. foreach ($array as $animal) {
  9.     $xml->push('animal', array('species' => $animal[0]));
  10.     $xml->element('name', $animal[2]);
  11.     $xml->element('food', $animal[1]);
  12.     $xml->pop();
  13. }
  14. $xml->pop();
  15. print $xml->getXml();

XML returned

XML:
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <zoo>
  3.   <animal species="monkey">
  4.     <name>Jim</name>
  5.     <food>banana</food>
  6.   </animal>
  7.   <animal species="hamster">
  8.     <name>Kola</name>
  9.     <food>apples</food>
  10.   </animal>
  11.   <animal species="turtle">
  12.     <name>Berty</name>
  13.     <food>beans</food>
  14.   </animal>
  15. </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