25.09.2014 Views

ZEND PHP 5 Certification STUDY GUIDE

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

XML and Web Services ” 199<br />

if ($use_xhtml) {<br />

echo $dom->saveXML();<br />

} else {<br />

echo $dom->saveHTML();<br />

}<br />

XPath Queries<br />

One of the most powerful parts of the DOM extension, is its integration with<br />

XPath—in fact, DomXPath is far more powerful than the SimpleXML equivalent:<br />

$dom = new DomDocument();<br />

$dom->load("library.xml");<br />

$xpath = new DomXPath($dom);<br />

$xpath->registerNamespace("lib", "http://example.org/library");<br />

$result = $xpath->query("//lib:title/text()");<br />

foreach ($result as $book) {<br />

echo $book->data;<br />

}<br />

This example seems quite complex, but in actuality it shows just how flexible the<br />

DOM XPath functionality can be.<br />

First, we instantiate a DomXpath object, passing in our DomDocument object so that<br />

the former will know what to work on. Next, we register only the namespaces we<br />

need, in this case the default namespace, associating it with the lib prefix. Finally,<br />

we execute our query and iterate over the results.<br />

A call to DomXpath::query() will return a DomNodeList object; you can find out how<br />

many items it contains by using the length property, and then access any one of them<br />

with the item() method. You can also iterate through the entire collection using a<br />

foreach() loop:<br />

Licensed to 482634 - Amber Barrow (itsadmin@deakin.edu.au)<br />

$result = $xpath->query("//lib:title/text()");

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!