phpdomzend-framework2web-scrapingzend-dom-query

Traversing through DOM element using PHP


I am useing Zend\Dom\Query to get specific content from a webpage. I have an html document like below

<html>
  <body>
     <div>
        <ul class="abcd">
            <li><a href="">Cow</a></li>
            <li><a href="">Goat</a></li>
        </ul>
        <ul class="abcd">
            <li><a href="">Mouse</a></li>
            <li><a href="">Keyboard</a></li>
        </ul>
        <ul class="abcd">
            <li><a href="">Bus</a></li>
            <li><a href="">Car</a></li>
        </ul>
     </div>
  </body>
</html>

From this document I would like to catch Bus,Car values.

How can I do this ??

How can I be expert in catching these type of values ?? Have you any tutorial on this ??

Thanks


Solution

  • Assuming you want all the link values:

    use Zend\Dom\Query;
    
    $dom = new Query($html);
    $links = $dom->execute('ul li a');
    
    foreach ($links as $link) {
        var_dump($link->nodeValue);
    }
    

    If you only want the values from the last list, and they all have the same class as in your example, try:

    $links = $dom->execute('ul[last()] li a');
    

    instead of the execute line above.