/** * This method enables us to add nice features to our xpath * implementation, like augmenting it with php functions so that we * can approach some of the functionality of XPath2. * * @param DOMDocument $dom * @return A new XPath object generated for the given dom. The object * will have all PHP functions registered to augment the native XPath1 * functions. * @author "David Hazel" <*****@*****.**> **/ public function generateXPathObject(DOMDocument $dom) { // create the object $xpath = new DOMXPath($this->domDocument); // Register the php: namespace (required for function augmenting) $xpath->registerNamespace("php", "http://php.net/xpath"); // Register PHP functions (no restrictions) $xpath->registerPHPFunctions(); // return the object return $xpath; }
$count = 0; $val = 0; foreach ($nodelist as $node) { $count++; $val += $node->textContent; } if ($val > 0) { return $val / $count; } else { return 0; } } $dom = new DOMDocument(); $dom->loadXML('<root xmlns="urn::default"><child>myval</child></root>'); $xpath = new DOMXPath($dom); $xpath->registerPHPFunctions('MyAverage'); $xpath->registerNamespace("php", "http://php.net/xpath"); $xpath->registerNamespace("def", "urn::default"); $nodelist = $xpath->query("//def:child"); if ($node = $nodelist->item(0)) { print $node->textContent . "\n"; } $count = $xpath->evaluate("count(//def:child)"); var_dump($count); $xpathdoc = $xpath->document; var_dump($xpathdoc instanceof DOMDocument); $root = $dom->documentElement; $root->appendChild($dom->createElementNS("urn::default", "testnode", 3)); $root->appendChild($dom->createElementNS("urn::default", "testnode", 4)); $root->appendChild($dom->createElementNS("urn::default", "testnode", 4)); $root->appendChild($dom->createElementNS("urn::default", "testnode", 5));
protected function xPathDOMFilter($doc, $path, $namespaces = array()) { $xPath = new \DOMXPath($doc); foreach ($namespaces as $prefix => $nsuri) { $xPath->registerNamespace($prefix, $nsuri); } $xPath->registerNamespace("php", "http://php.net/xpath"); $xPath->registerPHPFunctions(); $filtered = $xPath->query($path); $result = $this->createArray($filtered); return $result; }