Web Scraping how to insert the result into the <img src=

Asked

Viewed 239 times

0

I’m making a web scraping of a website, however I would like the returned images to come to me inside the <img src= but I’m not succeeding

// Find all images 
foreach($html->find('img') as $element) 
       echo $element->src . '<br>';

I tried it here for example but it didn’t work

<img src".$element->src .."> '<br>';

2 answers

3

The correct syntax, if in html is :

<img src="<?php echo $element->src;?>"/> 

3

You can use the XPath for this and use the getAttribute.

// Inicia o DOM:
$html = $retorno_do_seu_curl;

$dom = new DOMDocument;
$dom->loadHTML($html);

// Inicia XPath:
$xpath = new DomXPath($dom);

// Encontra todos os `<img>`.
$imagens = $xpath->query('//img');

// Faz um loop para cada imagem obtida:
foreach($imagens as $_imagem){

    // Obtem o `src` da respetiva imagem:
    echo '<img src="' . $_imagem->getAttribute('src') . '">';

}

Test this by clicking here.


If you don’t want to use the XPath just use the getElementsByTagName afterward getAttribute.

$dom = new DOMDocument;
$dom->loadHTML($html);

$imagens = $dom->getElementsByTagName('img');

foreach($imagens as $_imagem){

    echo '<img src="' . $_imagem->getAttribute('src') . '">';

}
  • Than you. Funciounou!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.