Serializing XML With PHP - A Twist In The Tale
(Page 2 of 10 )
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();
// create array to be serialized
$xml = array ( "book" => array (
"title" => "Oliver Twist",
"author" => "Charles Dickens"));
// perform serialization
$result = $serializer->serialize($xml);
// 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):
<array>
<book>
<title>Oliver Twist</title>
<author>Charles Dickens</author>
</book>
</array>
As you can see, the output of the script is a well-formed XML document -- all created using PHP code!
Next: Anatomy Class >>
More PHP Articles
More By Vikram Vaswani, (c) Melonfire