(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() 与 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 "找到 {$nodes->length} 本以 'PHP' 开头的书籍:\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() 与 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
示例 #4 DOMXPath::registerPHPFunctions() 与 可调用
<?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" => fn ($nodes) => 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