Search code examples
phpsimple-html-dom

How to get link using simple html dom


Html document is like this

<li><h2><a href="http://beezfeed.cu.ma">Beezfeed</h2></a></li>
<li><a href="http://beezfeed.cu.ma/kuto">Beezfeed kuto</a></li>
<li><a href="http://beezfeed.cu.ma/movies">Beezfeed movies</a></li>

Here I want the last two link href. Here is my code I am using simple html dom, so please answer me on this and can you please tell me in regex also.

$bb->load($str);
$link = $bb->find('div[class=azindex] li');

foreach ($link as $s) {
    $lin = $s->find("a");
    foreach ($lin as $li) {
        echo $li->href . "<br/>";
    }
}

I get all the link containing in li tag, But I do not want link that has h2 tag. Thanks in advance


Solution

  • If i had to do it in a simple way i would do it like this :

    $bb->load($str);
    $link=$bb->find('div[class=azindex] li');
    foreach($link as $s){
    $lin=$s->find("a");
    foreach($lin as $li){
        if(is_null($li->find("h2")) {
            echo $li->href."<br>";
        }
        /*Do nothing if h2 was found*/
    }
    }
    

    I just used the find method on the $li, if a h2 is found i do nothing, otherwise i print the line. I could not test it, i hope it helps a little.