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!
Let's take a closer look at how I accomplished this.
1. The first step is, obviously, to include the XML_Serializer class file:
<?php
// include class file include("Serializer.php");
? >
You can either provide an absolute path to this file, or do what most lazy programmers do -- include the path to your PEAR installation in PHP's include_path variable, so that you can access any of the PEAR classes without needing to type in long, convoluted file paths.
2. Next, an object of the class needs to be initialized, and assigned to a PHP variable.
<?php
// create object $serializer = new XML_Serializer();
? >
This variable serves as the control point for future manipulation of XML_Serializer properties and methods.
3. Next, you need to put together the data that you plan to encode in XML. The simplest way to do this is to create a nested set of arrays whose structure mimics that of the final XML document you desire.
4. With all the pieces in place, all that's left is to perform the transformation. This is done via the object's serialize() method, which accepts a PHP structure and returns a result code indicating whether or not the serialization was successful.
5. Once the serialization is complete, you can do something useful with it: write it to a file, pass it through a SAX parser or -- as I've done here -- simply output it to the screen for all to admire:
<?php
// check result code and display XML if success if($result === true) { echo $serializer->getSerializedData(); }
? >
The getSerializedData() method returns the serialized XML document tree as is, and serves a very useful purpose in debugging. (You'll see it often over the next few pages.)