Traversing the DOM with PHP's XPath ClassesThe DOM classes discussed in the previous section are more than adequate for most common tasks, but getting used to them can take awhile. Additionally, for long and complex documents containing a large number of elements and/or levels, progressing from node to node in an iterative manner can often be tedious.You can use a recursive function to simplify the process, but you'll still have to write a fair amount of code to create and manipulate node collections, which are at different levels of the tree. It's precisely to simplify this process that PHP also comes with a couple of XPath classes. XPath, as you may already know, is an addressing mechanism for XML documents, designed to allow XML document authors to quickly access node collections on the basis of both location and condition. A discussion of XPath is beyond the scope of this book, so I'll assume that you already know the basics of axes, predicates, and node tests. In case you don't, you might want to brush up on the basics before proceeding with this section. Go to the companion web site for this book http://www.xmlphp.com/ or http://www.newriders.com) to find a list of reference material to get you started. XPathContext and XPathObject ClassesPHP's XPath classes add flexibility to the DOM parser by freeing developers from the standard parent-child paradigm when constructing node collections.The XPath classes allow developers to quickly build node collections matching specific criteriafor example, every third element or every element containing the attribute shape=square with scant regard for their position in the hierarchical document tree. The XPathContext class is used to set up a context for all XPath evaluations, and is created by a call to the xpath_new_context() function. This function must be passed a reference to a DomDocument object. For example:
If you think this doesn't look very interesting, you're rightit's not. The XPathContext object merely sets up a context for all future XPath evaluations. These XPath evaluations usually result in instances of the XPathObject class, which are far more interesting. An instance of the XPathObject class may be created with a call to the xpath_eval() method of the XPathContext object, which requires an XPath address for evaluation. If the XPath evaluates successfully, xpath_eval() returns an instance of the XPathObject class containing a collection of nodes matching the specified XPath expression. Take a look at Listing 3.11, which uses an XPath address to isolate all the vegetable elements in the document: Listing 3.11 Creating Node Collections with XPath
When you examine the structure of the XPathObject object instance with print_r(), here's what you'll see:
As you can see, the object contains an array of DomElement objects, representing the element nodes matching the XPath expression. These DomElement objects can now be accessed and manipulated using standard class methods and properties. A Composite ExampleIn order to demonstrate just how powerful XPath can be, consider the following situation. In a research project conducted to study the effect of temperature on bacterial culture growth, researchers publish their findings as XML data. Listing 3.12 contains a sample of this data. Listing 3.12 A Compilation of Experiment Readings (data.xml)
It now becomes necessary to compile this raw data into an easily understandable table so that the results can be analyzed. Ideally, what is required is a 2x2 table displaying the temperature scale on the Y-axis and the culture type on the X-axis.The intersection of the two axes should be an average of all readings made for that culture at that temperature. With XPath, this is a snap to accomplish. Listing 3.13 demonstrates the script. Listing 3.13 Creating Node Collections with XPath
I've used three different XPath expressions here. The first two are used to create a list of available cultures and temperature points; these are required for the row and column headings of the table. The third XPath returns a list of nodes matching a specific culture and temperature. Now, all I need to do is add the readings associated with each of these nodes to reach a total number, and divide that total number by the number of nodes (readings) to obtain an average cell count. Figure 3.3 shows what the output looks like. Figure 3.3. Statistical analysis with Xpath.This kind of thing comes in particularly handy when you need to perform statistical analysis of sampling data; it provides a simple and easy way to bring together different elements of each sample, perform calculations on these elements, and relate them to each other in two or three dimensions. XPath's conditional expressions are a boon herealthough you can certainly do the same thing without XPath (and I encourage you to try, just so you have a better understanding of the difference), the process would be far more tedious. |