Feed Sign in with OpenID OpenID

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:

XmlWriter.class.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>

This is XmlWriter: Generating XML from PHP by Simon Willison, posted on 29th April 2003.

View blog reactions

Next: In praise of functional programming

Previous: Skill Swap

20 comments

  1. The approach I use for my "XML serializer" built into my XML-RPC library is just to take an ordinary PHP data structure and serialize it into XML. No object syntax necessary :) For attributes, you just have a key be something like $foo['tag attr']. Since you can't have a space in an XML tag, there's no problem. It's all of about 40 lines.

    Keith - 30th April 2003 03:20 - #

  2. Thanks Simon! This'll be useful.

    Bill Humphries - 30th April 2003 07:01 - #

  3. I've modified it slightly for support of <![CDATA[ ]]> tags thus:

    $this->xml .= '>'.htmlentities($content);.'</'.$element.'>'."\n" ;

    Becomes:

    if (!preg_match("/\<\!\[CDATA\[(.*)\]\]\>/", $content)){ $content = htmlentities($content); } $this->xml .= '>'.$content.'</'.$element.'>'."\n";

    And could we please have <br> tags? Code's complicated otherwise :-)

    Aquarion - 3rd May 2003 15:19 - #

  4. nice work - this is going to make my new task of writing a flash/php/mysql interactive extravaganza far easier :D

    Thanks

    beardman - 23rd July 2003 17:49 - #

  5. wwwwdsds

    www - 27th November 2003 11:42 - #

  6. Thanks for your useful code.

    I suggest replacing the htmlentities($value) calls with a call to a member function that replaces only &, < and > in body xml and ' and " in attributes as well as also calling the library function utf8_encode($value) to put the text in true utf-8

    XML does not know about the other html entities unless they are defined in a dtd or somesuch

    Matthew Carey - 7th March 2004 15:48 - #

  7. how deal with charset gb2312?

    ahu - 27th October 2004 16:59 - #

  8. I added an 'array2xml' method to make it easy to automatically convert existing PHP arrays into XML structures. // array2xml method - a simple example $xml = new XmlWriter(); $array = array("stocks"=>array("symbols"=>array("MSFT","GOO G","YHOO"))); $xml->array2xml($array); print $xml->getXml(); // array2xml method - a more complex example (adding attributes) $xml = new XmlWriter(); $array = array("stocks"=>array("symbols"=>array("MSFT","GOO G",array("YHOO",array("company"=>"Yahoo!","close"= >35))))); $xml->array2xml($array); print $xml->getXml();

    Justin - 8th July 2005 11:30 - #

  9. sdsdg

    Dinesh - 21st July 2005 12:15 - #

  10. safd

    dfasf - 21st July 2005 12:16 - #

  11. Hi

    Dinesh Kumar - 21st July 2005 12:17 - #

  12. disubfidsbfuisdiufsd

    Test - 6th January 2006 14:05 - #

  13. The XmlWriter class works so well but i can not parse the returned xml data using javascript! Please help

    Johnson - 14th February 2006 07:37 - #

  14. Very neat code... Thanks for your help.

    f1sher - 21st April 2006 15:44 - #

  15. Thanks... it's a good approach when DOMDocument failes .. because the guy that admin's my site .. hasn't got the latest version of php ... :D

    Lazar Mihai - 26th May 2006 14:23 - #

  16. xcvxcv

    xcvxc - 23rd June 2006 16:38 - #

  17. Great, now I dont have to bother with xmldom in creation. Great!

    Henrik - 19th August 2006 15:09 - #

  18. if you want to see the code written with the class in ffox you'll need to add the following line: header('Content-Type: text/xml'); when showing the xml

    xerch - 29th August 2006 15:53 - #

  19. Seems the XmlWriter.class.php don't work under PHP 5.1. Error returned was :-

    Fatal error: Cannot redeclare class xmlwriter in /var/www/web4/cgi-bin/includes/XmlWriter.class.inc on line 6

    Anyone have any idea how to overcome this beside downgrading to PHP 5.0

    Allie Syadiqin - 8th September 2006 15:10 - #

  20. I had the same error as Allie, fixed it by renaming the XmlWriter class to something else.

    Seb - 8th October 2006 17:23 - #

Comments are closed.

Previously hosted at http://simon.incutio.com/archive/2003/04/29/xmlWriter

A django site