Cheap Web Hosting for Developers

PHP, MySQL, Java, Unix Cheap Web Hosting

CHAPTER 6 DOCUMENT OBJECT MODEL (DOM) 217

Filed under: PHP and XML — webmaster @ 12:22

CHAPTER 6 DOCUMENT OBJECT MODEL (DOM) 217 XPath as the sole parameter. Using the DOMDocument object $dom, created from the document in Listing 6-1, you can instantiate a DOMXPath object: $domxpath = new DOMXPath($dom); This object has no built-in properties and, depending upon the version of PHP, implements at most three methods. Using the query() Method The query() method is available in all versions of PHP 5. It retrieves nodes from a tree using XPath expressions. No matter what expression is used, even those that return no nodes, a DOMNodelist object is returned. In the event the expression returns no nodes, as either a result of no matching nodes or a different return type, the resulting DOMNodelist is empty. This method takes one required parameter, the XPath expression as a string, and an optional second parameter, an object derived from the DOMNodeclass, which would be used as the context for the XPath expression. For example, you can query for the author node in the document with the expression /book/bookinfo/author: $list = $domxpath->query(”/book/bookinfo/author”); $author = $list->item(0); Examining the $author variable, you will see it refers to the author element in the document. You could then use this node as the context parameter to access the surname node: $list = $domxpath->query(”surname”, $author); $surname = $list->item(0); If you tried to return the contents of the surname element as a string via an XPath expression, you will see that a DOMNodeList object is returned but is empty: $list = $domxpath->query(”string(’/book/bookinfo/author/surname’)”); var_dump($list); print “Number of Nodes Returned: “.$list->length.”n”; The var_dump of the $list variable clearly shows that the object is a DOMNodeList. The list after that illustrates that the number of nodes contained, from the length property, is 0. Using the evaluate() Method PHP 5.1 added a method, evaluate(), so that additional types supported by XPath could be returned. This method takes the same parameters as the query method(): an object derived from a DOMNode class followed by an optional context parameter. Using this method, you would write the same expression to return the contents of the surname element as a string, as follows: $list = $domxpath->evaluate(”string(/book/bookinfo/author/surname)”); var_dump($list); The output for the var_dump in this case is much different. A DOMNodeList is not returned in this case. Instead a string is returned: string(8) “Richards”

Note: If you are looking for good and high quality web space to host and run your application check Lunarwebhost PHP MySQL Web Hosting services

No Comments

No comments yet.

RSS feed for comments on this post. TrackBack URI

Sorry, the comment form is closed at this time.

Powered by Cheap Web Hosting