Serializing XML With PHP - Anatomy Class
(Page 3 of 10 )
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.
<?php
// create array to be serialized
$xml = array ( "book" => array (
"title" => "Oliver Twist",
"author" => "Charles Dickens"));
? >
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.
<?php
// perform serialization
$result = $serializer->serialize($xml);
? >
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.)
Next: Total Satisfaction >>
More PHP Articles
More By Vikram Vaswani, (c) Melonfire