Serializing XML With PHP - An Object Lesson
(Page 6 of 10 )
You can also serialize objects, in much the same way as you serialize arrays. Take a look at the following example, which demonstrates how:
<?php
// object definition
class Automobile
{
// object properties
var $color;
var $year;
var $model;
function setAttributes($c, $y, $m)
{
$this->color = $c;
$this->year = $y;
$this->model = $m;
}
}
// include class file
include("Serializer.php");
// create object
$serializer = new XML_Serializer();
// create object to be serialized
$car = new Automobile;
$car->setAttributes("blue", 1982, "Mustang");
// add XML declaration
$serializer->setOption("addDecl", true);
// indent elements
$serializer->setOption("indent", " ");
// set name for root element
$serializer->setOption("rootName", "car");
// perform serialization
$result = $serializer->serialize($car);
// check result code and display XML if success
if($result === true)
{
echo $serializer->getSerializedData();
}
? >
In this example, I've first defined a class called Automobile, and created some methods and properties for it. Then, further down in the script, I've instantiated an object of the class and set some very specific values for the object's properties. This object has then been serialized via XML_Serializer's serialize() method.
Here's the result:
<?xml version="1.0"? >
<car>
<color>blue</color>
<year>1982</year>
<model>Mustang</model>
</car>
Next: Not My Type >>
More PHP Articles
More By Vikram Vaswani, (c) Melonfire