Serializing XML With PHP - Total Satisfaction
(Page 4 of 10 )
Now, if you're a nitpicker, the output of the example on the previous page still won't satisfy you. Here's why:
- The serialized XML document does not contain the XML declaration at the top.
- The root element of the document is called <array>, whereas what you actually want is for it to be <library>.
- The XML document is not correctly indented.
In order to account for these requirements, XML_Serializer comes with a setOption() method, which allows you to customize the behaviour of the serializer to your needs. To illustrate, consider the following example, which solves the first problem noted above:
<?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"));
// add XML declaration
$serializer->setOption("addDecl", true);
// perform serialization
$result = $serializer->serialize($xml);
// check result code and display XML if success
if($result === true)
{
echo $serializer->getSerializedData();
}
? >
Here's the output:
<?xml version="1.0"? >
<array>
<book>
<title>Oliver Twist</title>
<author>Charles Dickens</author>
</book>
</array>
Thus, the setOption() method takes two arguments -- a variable and its value -- and uses that information to tell the serializer how to return the XML document.
Next, how about fixing the root element and the indentation?
<?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"));
// add XML declaration
$serializer->setOption("addDecl", true);
// indent elements
$serializer->setOption("indent", " ");
// set name for root element
$serializer->setOption("rootName", "library");
// perform serialization
$result = $serializer->serialize($xml);
// check result code and display XML if success
if($result === true)
{
echo $serializer->getSerializedData();
}
? >
And here's the result:
<?xml version="1.0"? >
<library>
<book>
<title>Oliver Twist</title>
<author>Charles Dickens</author>
</book>
</library>
Pretty, isn't it?
Next: No Attribution >>
More PHP Articles
More By Vikram Vaswani, (c) Melonfire