简体   繁体   中英

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

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 simply do.. $('h5 > a') and this would give me all the links under h5.

how would i do this in php using DOMDocument methods? I tried using phpquery but for some reason it can't read the html page i'm trying to parse.

检索一个DOMElement他们的孩子,你有兴趣,并调用一个DOMElement ::的getElementsByTagName就可以了。

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
}

Get all h5 tags from it, and loop through each one, checking if it's parent is an a tag.

// ...
$h5s = $document->getElementsByTagName('h5');
$correct_tags = array();
foreach ($h5s as $h5) {
    if ($h5->parentNode->tagName == 'a') {
        $correct_tags[] = $h5;
    }
}
// do something with $correct_tags

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM