PHP DOMDocument : how to select all links under a specific tag

后端 未结 3 1537
耶瑟儿~
耶瑟儿~ 2021-01-23 15:33

I\'m just getting started with using php DOMDocument and am having a little trouble. How would I select all link nodes under a specific node lets say

in jquery i could

3条回答
  •  走了就别回头了
    2021-01-23 15:50

    As far as I know, jQuery rewrites the selector queries to XPath. Any node jQuery can select, XPath also can.

    h5 > a means select any a node for which the direct parent node is h5. This can easily be translated to a XPath query: //h5/a.

    So, using DOMDocument:

    $dom = new DOMDocument;
    $dom->loadHTML($html);
    
    $xpath = new DOMXPath($dom);
    $nodes = $xpath->query('//h5/a');
    
    foreach ($nodes as $node) {
       // do stuff
    }
    

提交回复
热议问题