zend_php_5_certification_study_guide

Page 204

XML and Web Services � 185

if ($use_xhtml) { echo $dom->saveXML(); } else { echo $dom->saveHTML(); }

XPath Queries One of the most powerful parts of the DOM extension, is its integration with XPath—in fact, DomXpath is far more powerful than the SimpleXML equivalent: $dom = new DomDocument(); $dom->load("library.xml"); $xpath = new DomXPath($dom); $xpath->registerNamespace("lib", "http://example.org/library"); $result = $xpath->query("//lib:title/text()"); foreach ($result as $book) { echo $book->data; }

This example seems quite complex, but in actuality it shows just how flexible the DOM XPath functionality can be. First, we instantiate a DomXpath object, passing in our DomDocument object so that the former will know what to work on. Next, we register only the namespaces we need, in this case the default namespace, associating it with the lib prefix. Finally, we execute our query and iterate over the results. A call to DomXpath::query() will return a DomNodeList object; you can find out how many items it contains by using the length property, and then access any one of them with the item() method. You can also iterate through the entire collection using a foreach() loop: $result = $xpath->query("//lib:title/text()");


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.