PHP and the DOM

I l @ ve RuBoard

PHP 4.0 comes with a primitive, though effective, implementation of the DOM, based on the libxml library. Created by Daniel Veillard, libxml (http://www.xmlsoft.org/) is a modular, standards-compliant C library that provides XML parsing capabilities to the GNOME project (http://www.gnome.org/).

If you're using a stock PHP binary, it's quite likely that you'll need to recompile PHP to add support for this library to your PHP build. (Detailed instructions for accomplishing this are available in Appendix A, "Recompiling PHP to Add XML Support.")

Under Construction

If you're planning on using PHP's DOM extension in your development activities, be warned that this extension is still under development and is, therefore, subject to change without notice. Consequently, DOM code that works with one version of PHP may need to be rewritten or retested with subsequent versions.

Note also that the examples in this chapter have been tested with the DOM extension that ships with PHP 4.1.1, and are not likely to work with earlier versions because PHP's DOM implementation underwent some fairly radical changes between the release of PHP 4.0.6 and PHP 4.1.1. If you're using an earlier PHP build, you might want to upgrade to PHP 4.1.1 in order to try out the examples in this chapter.

A Simple Example

When PHP parses an XML document, it creates a hierarchical tree structure (mirroring the structure of the document) that is composed of objects. Each of these objects has standard properties and methods, and you can use these properties and methods to traverse the object tree and access specific elements, attributes, or character data.

The best way to understand how this works is with a simple example. Take a look at Listing 3.2, which demonstrates the basic concepts of this technique by traversing a DOM tree to locate a particular type of element, and print its value.

Listing 3.2 Traversing a DOM Tree
 <?php  // XML data  $xml_string = "<?xml version='1.0'?>  <sentence>What a wonderful profusion of colors and smells in the market        <vegetable color='green'>cabbages</vegetable>,        <vegetable color='red'>tomatoes</vegetable>,        <fruit color='green'>apples</fruit>,        <vegetable color='purple'>aubergines</vegetable>,        <fruit color='yellow'>bananas</fruit>  </sentence>";  // create a DOM object from the XML data  if(!$doc = xmldoc($xml_string))  {       die("Error parsing XML");  }  // start at the root  $root = $doc->root();  // move down one level to the root's children  $children = $root->children();  // iterate through the list of children  foreach ($children as $child)  {     // if <vegetable> element      if ($child->tagname == "vegetable")      {           // go down one more level            // get the text node            $text = $child->children();            // print the content of the text node            echo "Found: " . $text[0]->content . "<br>";      }  }  ?> 

Let's go through Listing 3.2 step-by-step:

  1. The first order of business is to feed the parser the XML data, so that it can generate the DOM tree. This is accomplished via the xmldoc() function, which accepts a string of XML as argument, and creates a DOM object representing the XML data. (You can use xmldocfile() to parse an XML file instead of a string. Check out Listing 3.5 for an example.) The following line of code creates a DOM object, and assigns it to the PHP variable $doc :

     if(!$doc = xmldoc($xml_string))  {       die("Error parsing XML");  } 
  2. This newly created DOM object has certain properties and methods. One of the most important ones is the root() method, which returns an object representing the document's root element.

    The following line of code returns an object representing the document element, and assigns it to the PHP variable $root :

     $root = $doc->root(); 
  3. This returned node is itself an object, again with properties and methods of its own. These methods and properties provide information about the node, and its relationship to other nodes in the tree: its name and type, its parent, and its children. However, the elements I'm looking for aren't at this level ”they're one level deeper. And so I used the root node's children() method to obtain a list of the nodes below it in the document hierarchy:

     $children = $root->children(); 
  4. This list of child nodes is returned as an array containing both text and element nodes. All I need to do now is iterate through this node list, looking for vegetable elements. As and when I find these, I dive one level deeper into the tree to access the corresponding character data and print it (this is a snap, given that each text node has a content property).

     foreach ($children as $child)  {     // if <vegetable> element      if ($child->tagname == "vegetable")      {           // go down one more level            // get the text node            $text = $child->children();            // print the content of the text node            echo "Found: " . $text[0]->content . "<br>";      }  } 

    When this script runs, it produces the following output:

     Found: cabbages  Found: tomatoes  Found: aubergines 

As Listing 3.2 demonstrates, DOM tree traversal takes place primarily by exploiting the parent-child relationships that exist between the nodes of the tree. After traversal to a particular depth has been accomplished, node properties can be used to extract all required information from the tree.

I l @ ve RuBoard


XML and PHP
XML and PHP
ISBN: 0735712271
EAN: 2147483647
Year: 2002
Pages: 84

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net