PHP Portal » PHP Handbuch » DOMXPath::registerPhpFunctions

Werbung

DOMXPath::registerPhpFunctions


(PHP 5 >= 5.3.0)

DOMXPath::registerPhpFunctionsRegister PHP functions as XPath functions

Beschreibung

public void DOMXPath::registerPhpFunctions ([ mixed $restrict ] )

This method enables the ability to use PHP functions within XPath expressions.

Parameter-Liste

restrict

Use this parameter to only allow certain functions to be called from XPath.

This parameter can be either a string (a function name) or an array of function names.

Rückgabewerte

Es wird kein Wert zurückgegeben.

Beispiele

The following examples use book.xml which contains the following:

Beispiel #2 DOMXPath::registerPHPFunctions with php:functionString

PHP Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
$doc = new DOMDocument; $doc->load('book.xml'); $xpath = new DOMXPath($doc); // Register the php: namespace (required) $xpath->registerNamespace("php", "http://php.net/xpath"); // Register PHP functions (no restrictions) $xpath->registerPHPFunctions(); // Call substr function on the book title $nodes = $xpath->query('//book[php:functionString("substr", title, 0, 3) = "PHP"]'); echo "Found {$nodes->length} books starting with 'PHP':\n"; foreach ($nodes as $node) { $title = $node->getElementsByTagName("title")->item(0)->nodeValue; $author = $node->getElementsByTagName("author")->item(0)->nodeValue; echo "$title by $author\n"; }

Das oben gezeigte Beispiel erzeugt eine ähnliche Ausgabe wie:

Found 2 books starting with 'PHP':
PHP Basics by Jim Smith
PHP Secrets by Jenny Smythe

PHP Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
$doc = new DOMDocument; $doc->load('book.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"; }

Das oben gezeigte Beispiel erzeugt eine ähnliche Ausgabe wie:

Books with multiple authors:
PHP Basics

Siehe auch