PHP | DOMXPath registerPhpFunctions()函数
DOMXPath::registerPhpFunctions()函数是PHP中的一个内置函数,用于启用在 XPath 表达式中使用PHP函数的能力。
句法:
void DOMXPath::registerPhpFunctions( mixed $restrict )
参数:此函数接受一个可选的单个参数$restrict ,其中包含要限制的函数。
返回值:此函数不返回任何值。
下面给出的程序说明了PHP中的DOMXPath::registerPhpFunctions()函数:
方案一:
FOO BAR
Mr. A
Mr. B
FOO BAZ
Mr. C
XML;
// Load the XML
$document->loadXML($xml);
// Create a new DOMXPath instance
$xpath = new DOMXPath($document);
// Register the php: namespace
$xpath->registerNamespace("php",
"http://php.net/xpath");
// Register PHP functions
$xpath->registerPHPFunctions();
// Use the PHP function to find
// the books starting with FOO
$query = '//book[php:functionString('
. '"substr", title, 0, 3) = "FOO"]';
// Execute the query
$entries = $xpath->evaluate($query);
echo "Found $entries->length books"
. " starting with 'FOO':\n";
foreach ($entries as $node) {
$title = $node->getElementsByTagName(
"title")->item(0)->nodeValue;
echo "
$title";
}
?>
输出:
Found 2 books starting with 'FOO':
FOO BAR
FOO BAZ
方案二:
FOO BAR
Mr. A
Mr. B
FOO BAZ
Mr. C
XML;
// Load the XML
$document->loadXML($xml);
// Create a new DOMXPath instance
$xpath = new DOMXPath($document);
// Register the php: namespace
$xpath->registerNamespace("php",
"http://php.net/xpath");
// Register PHP functions
$xpath->registerPHPFunctions();
// Use the manually created
// PHP function in query
$query = '//book[php:function('
. '"has_multiple", author)]';
// Execute the query
$entries = $xpath->evaluate($query);
echo "Found $entries->length books "
. "with multiple authors:\n";
foreach ($entries as $node) {
$title = $node->getElementsByTagName(
"title")->item(0)->nodeValue;
echo "
$title";
}
function has_multiple($nodes) {
// Return true if more than
// one author is there
return count($nodes) > 1;
}
?>
输出:
Found 1 books with multiple authors:
FOO BAR
参考: https://www. PHP.net/manual/en/domxpath.registerphpfunctions。 PHP