(PHP 5 >= 5.3.0, PHP 7, PHP 8)
DOMXPath::registerPhpFunctions — 将 PHP 函数注册为 XPath 函数
此方法使您能够在 XPath 表达式中使用 PHP 函数。
不返回值。
以下示例使用 book.xml,其中包含以下内容
示例 #1 book.xml
<?xml version="1.0" encoding="UTF-8"?> <books> <book> <title>PHP Basics</title> <author>Jim Smith</author> <author>Jane Smith</author> </book> <book> <title>PHP Secrets</title> <author>Jenny Smythe</author> </book> <book> <title>XML basics</title> <author>Joe Black</author> </book> </books>
示例 #2 DOMXPath::registerPHPFunctions() with php:functionString
<?php
$doc = new DOMDocument;
$doc->load('book.xml');
$xpath = new DOMXPath($doc);
// 注册 php: 命名空间(必需)
$xpath->registerNamespace("php", "https://php.net/xpath");
// 注册 PHP 函数(无限制)
$xpath->registerPHPFunctions();
// 在书名上调用 substr 函数
$nodes = $xpath->query('//book[php:functionString("substr", title, 0, 3) = "PHP"]');
echo "找到以 'PHP' 开头的 {$nodes->length} 本书:\n";
foreach ($nodes as $node) {
$title = $node->getElementsByTagName("title")->item(0)->nodeValue;
$author = $node->getElementsByTagName("author")->item(0)->nodeValue;
echo "$title 作者 $author\n";
}
?>
上面的示例将输出类似于
Found 2 books starting with 'PHP': PHP Basics by Jim Smith PHP Secrets by Jenny Smythe
示例 #3 DOMXPath::registerPHPFunctions() with php:function
<?php
$doc = new DOMDocument;
$doc->load('book.xml');
$xpath = new DOMXPath($doc);
// 注册 php: 命名空间(必需)
$xpath->registerNamespace("php", "https://php.net/xpath");
// 注册 PHP 函数(只有 has_multiple)
$xpath->registerPHPFunctions("has_multiple");
function has_multiple($nodes) {
// 如果有多个作者,则返回 true
return count($nodes) > 1;
}
// 筛选有多个作者的书籍
$books = $xpath->query('//book[php:function("has_multiple", author)]');
echo "有多个作者的书籍:\n";
foreach ($books as $book) {
echo $book->getElementsByTagName("title")->item(0)->nodeValue . "\n";
}
?>
上面的示例将输出类似于
Books with multiple authors: PHP Basics