您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息
免费发信息
三六零分类信息网 > 吴忠分类信息网,免费分类信息发布

Serializing XML With PHP

2024/3/6 23:23:44发布22次查看
a article about pear/xml_serializing, very useful, the author might be trog, idon't know. the original link is:
http://www.melonfire.com/community/columns/trog/article.php?id=244&page=1
serializing xml with php
build nested xml documents from php data structures with xml_serializer
| letting the creative juices flow |
php has always been ahead of the curve when it comes to supporting new technologies - and xml is no exception. early versions of php came with basic xml support built in; newer versions improved on this by adding support for new xml protocols and technologies like the dom, wddx and soap, making php one of the most versatile and flexible tools for xml application development.
now, by default, all newer versions of php come with the xml sax parser enabled; however, the dom module needs to be explicitly turned on at compile time. if you don't have the ability to recompile your php build - and if you're sharing space on a server, it's quite likely you won't - then you're up a creek without a paddle if your application needs to dynamically create xml document instances.
so, a creative solution is needed. which is where this article comes in.
over the next few pages, i'm going to be introducing you to a free php class named xml_serializer, which allows you to create xml documents from php data structures like arrays and objects *without* requiring you to first recompile your php build for dom support. as you might imagine, this can come in handy in certain situations - for example, if you need a quick and dirty way to build an xml document tree from an external data source, like a mysql database or a structured text file. so keep reading - you might find the rest of this show interesting!
serializing xml with php
build nested xml documents from php data structures with xml_serializer
| a twist in the tale |
the xml_serializer class comes courtesy of pear, the php extension and application repository (http://pear.php.net), and has been developed by stephan schmidt of phptools.de fame. in case you didn't know, pear is an online repository of free php software, including classes and modules for everything from data archiving to xml parsing. when you install php, a whole bunch of pear modules get installed as well.
in case your php distribution didn't include xml_serializer, you can get yourself a copy from the official pear web site, at http://pear.php.net - simply unzip the distribution archive into your pear directory and you're ready to roll!
note that in order to use xml_serializer, you will need to have the xml_util package already installed. if you don't already have it, you can get it from the web site above.
let's begin with something simple - dynamically constructing an xml document from a php array. here's the code:
// 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));
// perform serialization
$result = $serializer->serialize($xml);
// check result code and display xml if success
if($result === true)
{
   echo $serializer->getserializeddata();
}
?>
don't worry if it didn't make too much sense - all will be explained shortly. for the moment, just feast your eyes on the output (note that you may need to use the view source feature of your browser to see this):
charles dickens
as you can see, the output of the script is a well-formed xml document - all created using php code!
serializing xml with php
build nested xml documents from php data structures with xml_serializer
| anatomy class |
let's take a closer look at how i accomplished this.
1. the first step is, obviously, to include the xml_serializer class file:
// include class file
include(serializer.php);
?>
you can either provide an absolute path to this file, or do what most lazy programmers do - include the path to your pear installation in php's include_path variable, so that you can access any of the pear classes without needing to type in long, convoluted file paths.
2. next, an object of the class needs to be initialized, and assigned to a php variable.
// create object
$serializer = new xml_serializer();
?>
this variable serves as the control point for future manipulation of xml_serializer properties and methods.
3. next, you need to put together the data that you plan to encode in xml. the simplest way to do this is to create a nested set of arrays whose structure mimics that of the final xml document you desire.
// create array to be serialized
$xml = array ( book => array (
            title => oliver twist,
            author => charles dickens));
?>
4. with all the pieces in place, all that's left is to perform the transformation. this is done via the object's serialize() method, which accepts a php structure and returns a result code indicating whether or not the serialization was successful.
// perform serialization
$result = $serializer->serialize($xml);
?>
5. once the serialization is complete, you can do something useful with it - write it to a file, pass it through a sax parser or - as i've done here - simply output it to the screen for all to admire:
// check result code and display xml if success
if($result === true)
{
   echo $serializer->getserializeddata();
}
?>
the getserializeddata() method returns the serialized xml document tree as is, and serves a very useful purpose in debugging - you'll see it often over the next few pages.
serializing xml with php
build nested xml documents from php data structures with xml_serializer
| total satisfaction |
now, if you're a nitpicker, the output of the example on the previous page still won't satisfy you. here's why:
1. the serialized xml document does not contain the xml declaration at the top.
2. the root element of the document is called , whereas what you actually want is for it to be .
3. 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:
// 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:
charles dickens
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?
// 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:
charles dickens
pretty, isn't it?
serializing xml with php
build nested xml documents from php data structures with xml_serializer
| no attribution |
now, what about those pesky attributes? well, xml_serializer comes with an option that allows you to represent array keys as attributes of the enclosing element (instead of elements themselves). take a look:
// 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);
// represent scalar values as attributes instead of element
$serializer->setoption(scalarasattributes, 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:
note that in order for this to work, the array key which is to be represented as an attribute should point to a single scalar value and not another array or object. to understand this better, consider the following example, which demonstrates the difference:
// 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,
            price => array (   currency => usd,
                     amount => 24.50)));
// add xml declaration
$serializer->setoption(adddecl, true);
// indent elements
$serializer->setoption(indent,     );
// set name for root element
$serializer->setoption(rootname, library);
// represent scalar values as attributes instead of element
$serializer->setoption(scalarasattributes, true);
// perform serialization
$result = $serializer->serialize($xml);
// check result code and display xml if success
if($result === true)
{
   echo $serializer->getserializeddata();
}
?>
and here's the revised output:
to add attributes to the root node, set them with the rootattributes option, as below:
// include class file
include(serializer.php);
// create object
$serializer = new xml_serializer();
// create array
$xml = array(name => john doe, age => 34, sex => male);
// add xml declaration
$serializer->setoption(adddecl, true);
// indent elements
$serializer->setoption(indent,     );
// set name for root element
$serializer->setoption(rootname, person);
// set attributes for root element
$serializer->setoption(rootattributes, array(id => 346747));
// perform serialization
$result = $serializer->serialize($xml);
// check result code and display xml if success
if($result === true)
{
   echo $serializer->getserializeddata();
}
?>
here's the output:
john doe
    34
    male
serializing xml with php
build nested xml documents from php data structures with xml_serializer
| an object lesson |
you can also serialize objects, in much the same way as you serialize arrays. take a look at the following example, which demonstrates how:
// 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:
blue
    1982
    mustang
serializing xml with php
build nested xml documents from php data structures with xml_serializer
| not my type |
one of xml_serializer's other interesting features is its ability to store data type information along with each value in the xml document. called type hints, this data type information can help in distinguishing between the integer 6 and the string 6, and comes in handy if your xml application is strongly typed.
to enable type hints, you need to simply set the typehints option to true. the following example illustrates:
// include class file
include(serializer.php);
// set options
$options = array(   adddecl => true,
         indent =>     ,
         rootname => car,
         typehints => true);
// create object
$serializer = new xml_serializer($options);
// create array
$car = array(color => blue, year => 1982, model => mustang, price => 15000.00);
// perform serialization
$result = $serializer->serialize($car);
// check result code and display xml if success
if($result === true)
{
   echo $serializer->getserializeddata();
}
?>
once type hints are enabled, every element within the xml document will bear an additional attribute indicating the data type of the value contained within it. here's what the output of the example above looks like:
blue
    1982
    mustang
    15000
note that in the example above, i've used a slightly different method to set serializer options - i've created an array of options and values, and passed the array to the object constructor. when you have a large number of options to set, this method can save you a few lines of code.
serializing xml with php
build nested xml documents from php data structures with xml_serializer
| travelling in reverse |
good things come in twos - mickey and donald, tom and jerry, yin and yang - and so it's no surprise that xml_serializer has a doppelganger of its own. called xml_unserializer, this class can take an xml document and convert it into a series of nested php structures, suitable for use in a php script.
in order to understand how this works, consider the following xml document:
arthur conan doyle
      24.95
yann martel
      7.99
lonely planet
      16.99
now, in order to convert this xml document into a php structure, simply put xml_unserializer to work on it, as below:
// include class file
include(unserializer.php);
// create object
$unserializer = &new xml_unserializer();
// unserialize the document
$result = $unserializer->unserialize(library.xml, true);
// dump the result
$data = $unserializer->getunserializeddata();
print_r($data);
?>
here, the unserialize() method accepts either a string containing xml data or an xml file (set the second argument to false or true depending on which one you are passing) and returns a php structure representing the xml document. here's what the output looks like:
array
(
    [book] => array
        (
            [0] => array
                (
                    [title] => the adventures of sherlock holmes
                    [author] => arthur conan doyle
                    [price] => 24.95
                )
[1] => array
                (
                    [title] => life of pi
                    [author] => yann martel
                    [price] => 7.99
                )
[2] => array
                (
                    [title] => europe on a shoestring
                    [author] => lonely planet
                    [price] => 16.99
                )
)
)
now, in order to access the title of the third book (for example), you would use the notation
$data['book'][2]['title'];
which would return
europe on a shoestring
note that xml_unserializer uses the type hints generated in the serialization process to accurately map xml elements to php data types. if these hints are unavailable (as in the example above), xml_unserializer will guess the type of each value. a look at the source code of the class reveals that complex structures will be arrays and tags with only cdata in them will be strings.
serializing xml with php
build nested xml documents from php data structures with xml_serializer
| keeping it simple |
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
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
serializing xml with php
build nested xml documents from php data structures with xml_serializer
| 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,
mysql> select * 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:
doe
        john
        27
        m
        engineering
        us
jones
        sue
        31
        f
        finance
        uk
woo
        david
        26
        m
        administration
        cn
thomas
        james
        34
        m
        finance
        us
kent
        jane
        29
        f
        administration
        us
kamath
        ravina
        35
        f
        finance
        in
with xml_serializer, accomplishing this is a matter of a few lines of code. here they are:
// 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.
serializing xml with php
build nested xml documents from php data structures with xml_serializer
| linking out |
and that's about it for this article. over the last few pages, i showed you how you to build an xml document tree even if your php build doesn't support the xml dom, via the free add-on xml_serializer class from pear. i showed you how to programmatically create an xml document from an array or an object, how to indent xml document nodes, how to attach attributes to elements, and how to customize the behaviour of the serializer. i also showed you to how to reverse-serialize xml documents into php arrays or objects for use within a php script, together with examples of how type hints could help to make this a more accurate process. finally, i wrapped things up with a composite example that demonstrated a practical, real-world use for all this code - converting the data in a mysql database into xml and writing it to a file.
all this is, of course, only the tip of the iceberg - there are an infinite number of possibilities with power like this at your disposal. to find out what else you can do with xml and php, i'd encourage you to visit the following links:
xml basics, at http://www.melonfire.com/community/columns/trog/article.php?id=78
xsl basics, at http://www.melonfire.com/community/columns/trog/article.php?id=82
using php with xml, at http://www.melonfire.com/community/columns/trog/article.php?id=71
xslt transformation with php and sablotron, at http://www.melonfire.com/community/columns/trog/article.php?id=97
building xml trees with php, at http://www.melonfire.com/community/columns/trog/article.php?id=180
the xml and php book, at http://www.xmlphp.com/
till next time...be good!
吴忠分类信息网,免费分类信息发布

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录