dongtu1789 2014-04-12 00:27
浏览 93

DomXPath:在DomXPath查询结果中搜索?

How can I query an xpath result for a sub element, without querying the entire document again?

I query my document to find the last <li> with the 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:

$p = $xpath->query( "//p[contains(concat(' ', normalize-space(@class), ' '), 'field-description')]" )->item( 0 );

A p tag with class field-description. 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:

$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.

  • 写回答

1条回答 默认 最新

  • dongzhi1822 2014-04-12 00:48
    关注

    The second argument to query is the contextnode, which limits the search to within that node. However, if you use an absolute xpath, query will still return nodes for the entire document.

    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. (HT: Alf Eaton)

    评论

报告相同问题?

悬赏问题

  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥50 我撰写的python爬虫爬不了 要爬的网址有反爬机制
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据