DOMXPath::registerPhpFunctions()函数是PHP中的内置函数,用于启用在XPath表达式中使用PHP函数的函数。
用法:
void DOMXPath::registerPhpFunctions( mixed $restrict )
参数:该函数接受可选的单个参数$restrict,该参数包含要限制的函数。
返回值:该函数不返回任何值。
下面给出的程序说明了PHP中的DOMXPath::registerPhpFunctions()函数:
程序1:
<?php
// Create a new DOMDocument instance
$document = new DOMDocument();
// Create a XML
$xml = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<books>
<book>
<title>FOO BAR</title>
<author>Mr. A</author>
<author>Mr. B</author>
</book>
<book>
<title>FOO BAZ</title>
<author>Mr. C</author>
</book>
</books>
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 "<br>$title";
}
?>输出:
Found 2 books starting with 'FOO': FOO BAR FOO BAZ
程序2:
<?php
// Create a new DOMDocument instance
$document = new DOMDocument();
// Create a XML
$xml = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<books>
<book>
<title>FOO BAR</title>
<author>Mr. A</author>
<author>Mr. B</author>
</book>
<book>
<title>FOO BAZ</title>
<author>Mr. C</author>
</book>
</books>
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 "<br>$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
相关用法
- PHP DOMXPath query()用法及代码示例
- d3.js d3.rgb()用法及代码示例
- PHP pi( )用法及代码示例
- d3.js d3.lab()用法及代码示例
- p5.js sin()用法及代码示例
- p5.js tan()用法及代码示例
- PHP min( )用法及代码示例
- PHP Ds\Map xor()用法及代码示例
- d3.js d3.map.set()用法及代码示例
- PHP Ds\Set get()用法及代码示例
- p5.js int()用法及代码示例
- PHP Ds\Map last()用法及代码示例
注:本文由纯净天空筛选整理自gurrrung大神的英文原创作品 PHP | DOMXPath registerPhpFunctions() Function。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。
