PHP | DOMXPath evaluate()函数
DOMXPath::evaluate()函数是PHP中的一个内置函数,用于执行给定的 XPath 表达式,该表达式是为选择一组节点而定义的模式。
句法:
mixed DOMXPath::evaluate( string $expression,
DOMNode $contextnode, bool $registerNodeNS )
参数:此函数接受三个参数,如上所述,如下所述:
- $expression:它指定要执行的 XPath 表达式。
- $contextnode (可选):它指定执行相对 XPath 查询的上下文节点。默认情况下,查询是相对于根元素的。
- $registerNodeNS (可选):它指定是否禁用上下文节点的自动注册。
返回值:此函数在成功时返回 TRUE。
异常:此函数在出错时抛出 DOMXPathException。
下面的例子说明了PHP中的DOMXPath::evaluate()函数:
示例 1:
php
GeeksforGeeks
400
Intro to XML
300
XML;
// Load the XML
$document->loadXML($xml);
// Create a new DOMXPath instance
$xpath = new DOMXPath($document);
// Get the
$tbody = $document->
getElementsByTagName('bookstore')->item(0);
// Query to get the number of titles with lang
// attribute "en"
$query = 'count(//title[@lang=\'en\'])';
// Evaluate the query
$entries = $xpath->evaluate($query, $tbody);
echo "Number of elements with lang = \"en\": $entries\n";
?>
php
Keep Learning.
XML;
// Load the XML
$document->loadXML($xml);
// Create a new DOMXPath instance
$xpath = new DOMXPath($document);
// Get the
$tbody = $document->
getElementsByTagName('GeeksforGeeks')->item(0);
// Get the element with name GeeksforGeeks
$query = '//GeeksforGeeks';
// Evaluate the query
$entries = $xpath->evaluate($query, $tbody);
echo $entries[0]->nodeValue;
?>
输出:
Number of elements with lang = "en": 2
示例 2:
PHP
Keep Learning.
XML;
// Load the XML
$document->loadXML($xml);
// Create a new DOMXPath instance
$xpath = new DOMXPath($document);
// Get the
$tbody = $document->
getElementsByTagName('GeeksforGeeks')->item(0);
// Get the element with name GeeksforGeeks
$query = '//GeeksforGeeks';
// Evaluate the query
$entries = $xpath->evaluate($query, $tbody);
echo $entries[0]->nodeValue;
?>
输出:
Keep Learning.
参考: https://www. PHP.net/manual/en/domxpath.evaluate。 PHP