Search code examples
phpparsingdomhtml-parsingsimple-html-dom

How parse images inside a web page with PHP?


I'm sure maybe is a duplicate but i have a problem with "parsing web page with PHP". I try to extrapolate src,alt and title of each element <img> inside a web page but i have this error:

Uncaught Error: Call to a member function getElementsByTagName() on array in /web/example.php:12 Stack trace: #0 {main} thrown in 

To do this i creates this small code:

include('../simple_html_dom.php');
$doc = file_get_html('https://www.example.com');

foreach($doc-> find('div.content')-> getElementsByTagName('img') as $item){
    $src =  $item->getAttribute('src');
    $title= $item->getAttribute('title');
    $alt= $item->getAttribute('alt');

    echo "\n";
    echo $src;
    echo $title;
    echo $alt;
}

I hope you can help me.... thanks a lot and sorry for my english


Solution

  • find returns an array of elements, so you need to iterate over each of those as well:

    foreach($doc->find('div.content') as $div) {
        foreach ($div->getElementsByTagName('img') as $item){
            $src =  $item->getAttribute('src');
            $title= $item->getAttribute('title');
            $alt= $item->getAttribute('alt');
    
            echo "\n";
            echo $src;
            echo $title;
            echo $alt;
        }
    }