[英]DomXPath: Search inside DomXPath query result?
How can I query an xpath result for a sub element, without querying the entire document again? 如何查询子元素的xpath结果,而无需再次查询整个文档?
I query my document to find the last <li>
with the class menu-item
: 我查询我的文档以找到最后一个
<li>
类class menu-item
:
$doc = new DomDocument();
@$doc->loadHTML( $html );
// $html is invalid (and should be at this point),
// so use @ sign to suppress errors
$xpath = new DomXPath( $doc );
$li = $xpath->query( "(//li[contains(concat(' ', normalize-space(@class), ' '), 'menu-item')])[last()]" )->item( 0 );
The above works just fine, now I want to query $li
to find the following: 上面的工作很好,现在我要查询
$li
以查找以下内容:
$p = $xpath->query( "//p[contains(concat(' ', normalize-space(@class), ' '), 'field-description')]" )->item( 0 );
A p
tag with class field-description
. 具有类
field-description
p
标签。 This does not work and returns the first instance found, if I modify it and use the [last()]
(whatever this is) then it works, but it's not necessarily the optimal solution here: 这不起作用并返回找到的第一个实例,如果我对其进行修改并使用
[last()]
(无论这是什么),则它可以工作,但不一定是这里的最佳解决方案:
$p = $xpath->query( "(//p[contains(concat(' ', normalize-space(@class), ' '), 'field-description')])[last()]" )->item( 0 );
The above line works, but I want to query inside $li
not the entire document again. 上面的行有效,但是我想在
$li
内部而不是整个文档中再次查询。
The second argument to query
is the contextnode
, which limits the search to within that node. query
的第二个参数是contextnode
,它将搜索限制在该节点内。 However, if you use an absolute xpath, query
will still return nodes for the entire document. 但是,如果使用绝对xpath,
query
仍将返回整个文档的节点。
php > $dd = new DomDocument();
php > // deliberately using malformed html.
php > $dd->loadhtml('<html><head><title>wat</title></head><body><div>Hello, <p>world</p></div><div class="container"><p>I like pie</div></body></html>');
php > $xp = new DomXPath($dd);
php > $container = $xp->query('//div[@class="container"]')->item(0);
php > var_dump($xp->query('//p'));
class DOMNodeList#6 (1) {
public $length =>
int(2)
}
php > var_dump($xp->query('//p', $container));
class DOMNodeList#4 (1) {
public $length =>
int(2)
}
php > var_dump($xp->query('p', $container));
class DOMNodeList#5 (1) {
public $length =>
int(1)
}
You can use a pattern like .//x
to match all x
elements recursively within a context node. 您可以使用
.//x
类的模式来在上下文节点中递归匹配所有x
元素。 (HT: Alf Eaton ) (HT: 阿尔夫·伊顿 )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.