Simplify the task of creating XML documents with the XML_Serializer class, which lets you build nested XML documents from PHP data structures like arrays and objects (and vice versa). I'll show you how to build an XML document tree via the XML_Serializer class from PEAR, how to programmatically create an XML document from an array or an object, how to attach attributes to elements, and how to customize the behavior of the serializer. All this, and much, much more!
The XML_Serializer class comes courtesy of PEAR, the PHP Extension and Application Repository (http://pear.php.net), and has been developed by Stephan Schmidt of phptools.de fame. In case you didn't know, PEAR is an online repository of free PHP software, including classes and modules for everything from data archiving to XML parsing. When you install PHP, a whole bunch of PEAR modules get installed as well.
In case your PHP distribution didn't include XML_Serializer, you can get yourself a copy from the official PEAR Web site, at http://pear.php.net - simply unzip the distribution archive into your PEAR directory and you're ready to roll!
Note that in order to use XML_Serializer, you will need to have the XML_Util package already installed. If you don't already have it, you can get it from the Web site above.
Let's begin with something simple: dynamically constructing an XML document from a PHP array. Here's the code:
<?php
// include class file include("Serializer.php");
// create object $serializer = new XML_Serializer();
// check result code and display XML if success if($result === true) { echo $serializer->getSerializedData(); }
? >
Don't worry if it didn't make too much sense; all will be explained shortly. For the moment, just feast your eyes on the output (note that you may need to use the "View Source" feature of your browser to see this):