Search code examples
phpelementsimple-html-dom

how to get href from within element using php and simple html dom


I have an html page that looks a bit like this

xxxx
<a href="www.google.com">google!</a>

<div class="big-div">
    <a href="http://www.url.com/123" title="123">
    <div class="little-div">xxx</div></a>

    <a href="http://www.url.com/456" title="456">
    <div class="little-div">xxx</div></a>
</div>
xxxx

I am trying to pull of the href's out of the big-div. I can get all the href's out of the whole page by using code like below.

$links = $html->find ('a');
foreach ($links as $link) 
{
    echo $link->href.'<br>';
}

But how do I get only the href's within the div "big-div". Edit: I think I got it. For those that care:

foreach ($html->find('div[class=big-div]') as $element) {
            $links = $element->find('a');
            foreach ($links as $link) {
                echo $link->href.'<br>';
            }
        }

Solution

  • The documentation is useful:

    $html->find(".big-div")->find('a');
    

    And then proceed to get the href and whatever other attributes you are interested in.

    Edit: The above would be the general idea. I've never used Simple HTML DOM, so perhaps you need to tweak the syntax somewhat. Try:

    foreach($html->find('.big-div') as $bigDiv) {
       $link = $bigDiv->find('a');
       echo $link->href . '<br>';
    }
    

    or perhaps:

    $bigDivs = $html->find('.big-div');
    
    foreach($bigDivs as $div) {
        $link = $div->find('a');
        echo $link->href . '<br>';
    }