PHP
  Home arrow PHP arrow Page 9 - Serializing XML With PHP
Dev Shed Forums  
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Smartphone Development  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Mobile Linux  
App Generation ROI  
IBM® developerWorks  
Forums Sitemap  
E-Commerce Hosting  
Linux Web Hosting  
Managed Hosting  
Small Business Hosting  
VPS Hosting  
Weekly Newsletter

 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid  
Request Media Kit
Contact Us  
Site Map  
Privacy Policy  
Support  
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
PHP

Serializing XML With PHP
By: Melonfire
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 72
    2004-04-14


    Table of Contents:
  • Serializing XML With PHP
  • A Twist In The Tale
  • Anatomy Class
  • Total Satisfaction
  • No Attribution
  • An Object Lesson
  • Not My Type
  • Travelling In Reverse
  • Keeping It Simple
  • Linking Out

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      error-file:tidyout.log Del.ici.ous error-file:tidyout.log Digg
      error-file:tidyout.log Blink error-file:tidyout.log Simpy
      error-file:tidyout.log Google error-file:tidyout.log Spurl
      error-file:tidyout.log Y! MyWeb error-file:tidyout.log Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article

     
     
    ADVERTISEMENT


    Serializing XML With PHP - Keeping It Simple
    ( Page 9 of 10 )

    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
     

       

    PHP ARTICLES

    - Building Dynamic Queries with Chainable Meth...
    - PHP Encryption and Decryption Methods
    - Building a MySQL Abstraction Class with Meth...
    - Completing a Sample String Processor with Me...
    - Mastering WHILE Loops for PHP and MySQL
    - Method Chaining: Adding More Methods to the ...
    - Method Chaining in PHP 5
    - The Role of Interfaces in Applying the Depen...
    - Dependency Injection: Using a Setter Method ...
    - Using a Model Class with the Dependency Inje...
    - Injecting Objects Using Setter Methods with ...
    - Injecting Objects by Constructor with the De...
    - The Dependency Injection Design Pattern in P...
    - Performing Inferential Statistical Analysis ...
    - Performing Descriptive Statistical Analysis ...





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 2 Hosted by Hostway
    Stay green...Green IT