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:
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>
Keith - 30th April 2003 03:20 - #
Bill Humphries - 30th April 2003 07:01 - #
$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 - #
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 - #
www - 27th November 2003 11:42 - #
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 - #
ahu - 27th October 2004 16:59 - #
Justin - 8th July 2005 11:30 - #
Dinesh - 21st July 2005 12:15 - #
dfasf - 21st July 2005 12:16 - #
Dinesh Kumar - 21st July 2005 12:17 - #
Test - 6th January 2006 14:05 - #
Johnson - 14th February 2006 07:37 - #
f1sher - 21st April 2006 15:44 - #
Lazar Mihai - 26th May 2006 14:23 - #
xcvxc - 23rd June 2006 16:38 - #
Henrik - 19th August 2006 15:09 - #
xerch - 29th August 2006 15:53 - #
Allie Syadiqin - 8th September 2006 15:10 - #
Seb - 8th October 2006 17:23 - #