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.

194 ” XML and Web Services<br />

What this example doesn’t show is that you may also iterate through the the children<br />

and attributes of $subchild and so forth using either a recursive function or an iterator<br />

(explained in the Design and Theory chapter), it is possible to access every single<br />

child and attribute at every depth of the XML document.<br />

XPath Queries<br />

The XML Path Language (XPath) is a W3C standardized language that is used to access<br />

and search XML documents. It is used extensively in Extensible Stylesheet Language<br />

Transformations (XSLT) and forms the basis of XML Query (XQuery) and XML<br />

Pointer (XPointer). Think of it as a query language for retrieving data from an XML<br />

document. XPath can be a very complex language, and with this complexity comes<br />

a lot of power, which SimpleXML leverages with the SimpleXMLElement::xpath()<br />

method.<br />

Using SimpleXMLElement::xpath(), you can run an Xpath query on any<br />

SimpleXMLElement object. If used on the root element, it will search the entire XML<br />

document. If used on a child, it will search the child and any children it may have.<br />

The following illustrates an XPath query on both the root element and a child node.<br />

XPath returns an array of SimpleXMLElement objects—even if only a single element is<br />

returned.<br />

// Search the root element<br />

$results = $library->xpath(’/library/book/title’);<br />

foreach ($results as $title)<br />

{<br />

echo $title . "\n";<br />

}<br />

// Search the first child element<br />

$results = $library->book[0]->xpath(’title’);<br />

foreach ($results as $title)<br />

{<br />

echo $title . "\n";<br />

}<br />

Licensed to 482634 - Amber Barrow (itsadmin@deakin.edu.au)

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

Saved successfully!

Ooh no, something went wrong!