1

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?

4

3 回答 3

2

尝试这个:-

<?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>'; 
}
?>
于 2012-08-03T06:09:52.127 回答
0

您可以使用 PHP 提供的 DOM 解析器来获取第一张图片的 src,如下所示:

$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";
}
于 2012-08-03T05:31:50.010 回答
0

你错过了第一'行中的第一个!!!

代替:

require_once( simple_html_dom.php');

和:

require_once( 'simple_html_dom.php');
于 2012-08-03T05:09:30.607 回答