How can I use PHP Simple HTML DOM to get the contents of a tags attribute?

3.7k views Asked by At

I want to get the contents of the src attribute of an <img> tag. Here is the code I'm using:

require_once( 'simple_html_dom.php');

$curl = curl_init(); 
curl_setopt($curl, CURLOPT_URL, $webpage);  
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);  
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 10);  
$str = curl_exec($curl);  
curl_close($curl);  

if( $str )
{
    $html= str_get_html($str);
    $img = $html->find('img', 0); // get the first image on the page
    $src = $img->src; // get the contents of the img src - but it doesn't seem to work
}

What am I doing wrong?

3

There are 3 answers

2
Praveen Kumar Purushothaman On

You are missing a first ' in the first line!!!

Replace:

require_once( simple_html_dom.php');

With:

require_once( 'simple_html_dom.php');
0
anubhava On

You can use PHP provided DOM parser to get 1st image's src like this:

$curl = curl_init(); 
curl_setopt($curl, CURLOPT_URL, $webpage);  
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);  
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 10);  
$html = curl_exec($curl);
curl_close($curl);  

if( !empty($html) ) {
   $doc = new DOMDocument;
   libxml_use_internal_errors(true);
   $doc->loadHTML($html);
   #echo $doc->saveHTML();
   $xpath = new DOMXPath($doc);
   $src = $xpath->evaluate("string(//img/@src)");
   echo "src=" . $src . "\n";
}
0
Abid Hussain On

Try this:-

<?php
include("simple_html_dom.php");

$webpage ="http://www.santabanta.com";

$html = file_get_html($webpage);

foreach($html->find('img') as $element) {
    echo $element->src . '<br>'; 
}
?>