我想获取src
标记的<img>
属性的内容。这是我正在使用的代码:
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
}
我做错了什么?
答案 0 :(得分: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>';
}
?>
答案 1 :(得分:0)
'
!!! 替换:
require_once( simple_html_dom.php');
使用:
require_once( 'simple_html_dom.php');
答案 2 :(得分: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";
}