Home arrow PHP arrow Page 9 - Serializing XML With PHP

Keeping It Simple - PHP

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!

  1. Serializing XML With PHP
  2. A Twist In The Tale
  3. Anatomy Class
  4. Total Satisfaction
  5. No Attribution
  6. An Object Lesson
  7. Not My Type
  8. Travelling In Reverse
  9. Keeping It Simple
  10. Linking Out
By: Melonfire
Rating: starstarstarstarstar / 73
April 14, 2004

print this article



It's also possible to convert an XML document into a PHP object instead of a nested set of arrays, simply by setting appropriate options for the unserializer. Consider the following example, which demonstrates how this may be done:

// include class file
// tell the unserializer to create an object
$options = array("complexType" => "object");
// create object
$unserializer = &new XML_Unserializer($options);
// unserialize the document
$result = $unserializer->unserialize("library.xml", true);    
// dump the result
? >

Here's the output:

stdClass Object
[book] => Array
[0] => stdClass Object
[title] => The Adventures of Sherlock Holmes
[author] => Arthur Conan Doyle
[price] => 24.95
1] => stdClass Object
[title] => Life of Pi
[author] => Yann Martel
[price] => 7.99
2] => stdClass Object
[title] => Europe on a Shoestring
[author] => Lonely Planet
[price] => 16.99

In this format, you can use standard object notation to access (for example) the title of the last book. The notation


would return

Europe on a Shoestring

* Employment Options

Now, while all this is fine and dandy, how about using all this new-found knowledge for something practical?

This next example does just that, demonstrating how the XML_Serializer class can be used to convert data stored in a MySQL database into an XML document, and write it to a file for later use. Here's the MySQL table I'll be using,

mysqlSELECT FROM employees;
id  lname  fname  age sex department     country |
|  54 Doe    John   |  27 M   Engineering    US      |
127 Jones  Sue    |  31 F   Finance        UK      |
113 Woo    David  |  26 M   Administration CN      |
175 Thomas James  |  34 M   Finance        US      |
168 Kent   Jane   |  29 F   Administration US      |
|  12 Kamath Ravina |  35 F   Finance        IN      |
6 rows in set 
(0.11 sec)

and here's what I want my target XML document to look like:

<?xml version="1.0"? >

With XML_Serializer, accomplishing this is a matter of a few lines of code. Here they are:

// include class file
// set output filename
$filename = 'employees.xml';
// set options
$options = array( "addDecl" => true,
   "defaultTagName" => "employee",
   "indent" => "    ",
   "rootName" => "employees");
// create object
$serializer = new XML_Serializer($options);
// open connection to database
$connection = mysql_connect("localhost", "user", "secret") or die
("Unable to connect!");
// select database
mysql_select_db("db1") or die ("Unable to select database!");
// execute query
$query = "SELECT * FROM employees";
$result = mysql_query($query) or die ("Error in query: $query. " .
// iterate through rows and print column data
while ($row = mysql_fetch_array($result))
 $xml[] = array ( "lname" => $row[1],
    "fname" => $row[2],
    "age" => $row[3],
    "sex" => $row[4],
    "department" => $row[5],
    "country" => $row[6]);
// close database connection
// perform serialization
$result = $serializer->serialize($xml);
// open file
if (!$handle = fopen($filename, 'w')) 

 print "Cannot open file ($filename)";
// write XML to file
if (!fwrite($handle, $serializer->getSerializedData())) 
 print "Cannot write to file ($filename)";
// close file    
? >

Pretty simple, once you know how it works. First, I've opened up a connection to the database and retrieved all the records from the table. Then I've instantiated a new document tree and iterated over the result set, adding a new set of nodes to the tree at each iteration. Finally, once all the rows have been processed, the dynamically generated tree is written to a file for later use.

>>> More PHP Articles          >>> More By Vikram Vaswani, (c) Melonfire

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort


- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates


Dev Shed Tutorial Topics: