简体   繁体   中英

domXpath get ancestor node

I have the following html structure :

<a class="class1" href="link">
   <div class="class2" id="result_0">
      <img imgstuffhere />      
         <div class="class3">
           <span>text</span>
        </div>
   </div>
</a>
<a class="class1" href="link">
   <div class="class2" id="result_0">
      <img imgstuffhere />      
         <div class="class3">
           <span>text</span>
        </div>
   </div>
</a>
etc....

I'm parsing the page using domXPath. I'm able to get each block by doing

$items = $xpath->query("//*[contains(concat(' ', normalize-space(@class), ' '), ' class1 ')]");

then i loop on items set of results :

foreach($items as $item){
    $name = $xpath->query("descendant::*[contains(concat(' ', normalize-space(@class), ' '), ' class3 ')]", $item)->item(0)->nodeValue;
    etc...
}

My problem is, in the loop, i need to get the href link located in the class1 node.

I tried to play around with ancestor stuff, but impossible to make it works.

ANSWER

$link = $item->getAttribute('href');

Simply did the trick.

$item is a DomNode representing the a element you selected.

It has an attributes property which is a DOMNamedNodeMap you should be able to access. If the property you want is href:

$link = $item->attributes->getNamedItem("href")->nodeValue; 

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