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!

TABLE OF CONTENTS:
  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
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

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:


<?php
 
// include class file
include("Unserializer.php");
 
// 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
print_r($unserializer->getUnserializedData());
 
? >

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


$obj->book[2]->title

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"? >
<employees>
    
<employee>
        
<lname>Doe</lname>
        
<fname>John</fname>
        
<age>27</age>
        
<sex>M</sex>
        
<department>Engineering</department>
        
<country>US</country>
    
</employee>
    
<employee>
        
<lname>Jones</lname>
        
<fname>Sue</fname>
        
<age>31</age>
        
<sex>F</sex>
        
<department>Finance</department>
        
<country>UK</country>
    
</employee>
    
<employee>
        
<lname>Woo</lname>
        
<fname>David</fname>
        
<age>26</age>
        
<sex>M</sex>
        
<department>Administration</department>
        
<country>CN</country>
    
</employee>
    
<employee>
        
<lname>Thomas</lname>
        
<fname>James</fname>
        
<age>34</age>
        
<sex>M</sex>
        
<department>Finance</department>
        
<country>US</country>
    
</employee>
    
<employee>
        
<lname>Kent</lname>
        
<fname>Jane</fname>
        
<age>29</age>
        
<sex>F</sex>
        
<department>Administration</department>
        
<country>US</country>
    
</employee>
    
<employee>
        
<lname>Kamath</lname>
        
<fname>Ravina</fname>
        
<age>35</age>
        
<sex>F</sex>
        
<department>Finance</department>
        
<country>IN</country>
    
</employee>
</employees>

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


<?php
 
// include class file
include("Serializer.php");
 
// 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. " .
mysql_error());
 
// 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
mysql_close($connection);
 
// perform serialization
$result = $serializer->serialize($xml);
 
// open file
if (!$handle = fopen($filename, 'w')) 

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

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
   

PHP ARTICLES

- 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: