MENU
PHP XPath
Query a loaded DOMDocument with its companion class, DOMXPath. evaluate() returns a native PHP value (number, string, or boolean) when the XPath expression's result is not a node-set, and a DOMNodeList otherwise. query() always returns a DOMNodeList, even for an expression such as count(...) that yields a number – converting that DOMNodeList to a string (for example via echo) raises a fatal error.DOMXPath
| readonly DOMDocument $document; |
|
__construct(DOMDocument $doc) mixed evaluate(string $expression [, DOMNode $contextnode [, bool $registerNodeNS = true]]) DOMNodeList query(string $expression [, DOMNode $contextnode [, bool $registerNodeNS = true]]) bool registerNamespace(string $prefix, string $namespaceURI) void registerPhpFunctions([mixed $restrict]) |
ch08-xpath-people.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<!-- people.xml -->
<people>
<person id="p3">
<name>Eric Lee</name>
<gender>m</gender>
<age>35</age>
</person>
<person id="p4">
<name>Serena</name>
<gender>f</gender>
<age>25</age>
</person>
</people><!DOCTYPE html>
<html><head></head><body><?php
$doc = new DOMDocument();
$doc->load('people.xml');
$xpath = new DOMXPath($doc);
$query = 'count(/people/person/name)';
echo $xpath->evaluate($query); //2
echo $xpath->query($query); // error
?></body></html>2
Catchable fatal error: Object of class DOMNodeList could not be converted to string in C:\Program Files\Zend\Apache2\htdocs\xml\people2.php on line 9