PHP and the DOM
PHP 4.0 comes with a primitive, though effective, implementation of the DOM, based on the libxml library. Created by Daniel Veillard, libxml (Appendix A, "Recompiling PHP to Add XML Support.")
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.
Let's go through Listing 3.2 step-by-step:
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:
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:
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 levelthey'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:
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).
When this script runs, it produces the following output:
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.