Register PHP functions as XPath functions in PHP

Description

The following code shows how to register PHP functions as XPath functions.

Example


/*from w  w w  . ja  v a2 s. c o  m*/
<?php
$doc = new DOMDocument;
$doc->load('test.xml');

$xpath = new DOMXPath($doc);

// Register the php: namespace (required)
$xpath->registerNamespace("php", "http://php.net/xpath");

// Register PHP functions (has_multiple only)
$xpath->registerPHPFunctions("has_multiple");

function has_multiple($nodes) {
    // Return true if more than one author
    return count($nodes) > 1;
}
// Filter books with multiple authors
$books = $xpath->query('//book[php:function("has_multiple", author)]');

echo "Books with multiple authors:\n";
foreach ($books as $book) {
    echo $book->getElementsByTagName("title")->item(0)->nodeValue . "\n";
}

?>

The following code is for book.xml.


<?xml version="1.0" encoding="UTF-8"?>
<books>/*from   ww  w  . j av a2s.  co  m*/
 <book>
  <title>PHP Basics</title>
  <author>Tom</author>
  <author>Jack</author>
 </book>
 <book>
  <title>PHP Secrets</title>
  <author>Jenny</author>
 </book>
 <book>
  <title>XML basics</title>
  <author>Joe</author>
 </book>
</books>

The code above generates the following result.





















Home »
  PHP Tutorial »
    XML »




DOM
SimpleXML
SimpleXMLElement
XML Parser