DOMXPath::query
DOMXPath::query
(PHP 5, PHP 7)
DOMXPath :: query - 计算给定的XPath表达式
描述
public DOMNodeList DOMXPath::query ( string $expression [, DOMNode $contextnode [, bool $registerNodeNS = true ]] )
执行给定的XPath expression
。
参数
expression
要执行的XPath表达式。
contextnode
可选项contextnode
可以指定用于执行相对XPath查询。默认情况下,查询是相对于根元素的。
registerNodeNS
可选的registerNodeNS
可以被指定来禁用上下文节点的自动登记。
返回值
返回包含与给定XPath匹配的所有节点的DOMNodeList expression
。任何不返回节点的表达式都会返回一个空的DOMNodeList。
如果expression
格式不正确或者contextnode
无效,则
返回DOMXPath :: query()FALSE
。
更新日志
版 | 描述 |
---|---|
5.3.3 | registerNodeNS参数已添加。 |
例子
示例#1获取所有英文书籍
<?php
$doc = new DOMDocument;
// We don't want to bother with white spaces
$doc->preserveWhiteSpace = false;
$doc->Load('book.xml'
$xpath = new DOMXPath($doc
// We starts from the root element
$query = '//book/chapter/para/informaltable/tgroup/tbody/row/entry[. = "en"]';
$entries = $xpath->query($query
foreach ($entries as $entry) {
echo "Found {$entry->previousSibling->previousSibling->nodeValue}," .
" by {$entry->previousSibling->nodeValue}\n";
}
?>
上面的例子将输出:
Found The Grapes of Wrath, by John Steinbeck
Found The Pearl, by John Steinbeck
我们也可以使用contextnode
参数来缩短我们的表达式:
<?php
$doc = new DOMDocument;
$doc->preserveWhiteSpace = false;
$doc->load('book.xml'
$xpath = new DOMXPath($doc
$tbody = $doc->getElementsByTagName('tbody')->item(0
// our query is relative to the tbody node
$query = 'row/entry[. = "en"]';
$entries = $xpath->query($query, $tbody
foreach ($entries as $entry) {
echo "Found {$entry->previousSibling->previousSibling->nodeValue}," .
" by {$entry->previousSibling->nodeValue}\n";
}
?>