使用DOMDocument从网站上抓取所有图像

Leo*_*nid 2 php kohana-3.2

我基本上想要使用DOMDocument在任何网站上获取所有图像.但由于某些我还不知道的原因,我甚至无法加载我的HTML.

$url="http://<any_url_here>/";
$dom = new DOMDocument();
@$dom->loadHTML($url); //i have also tried removing @
$dom->preserveWhiteSpace = false;
$dom->saveHTML();
$images = $dom->getElementsByTagName('img');
foreach ($images as $image) 
{
echo $image->getAttribute('src');
}
Run Code Online (Sandbox Code Playgroud)

发生的事情是没有打印出来.或者我是否对代码做错了什么?

S.V*_*ser 13

你没有得到结果因为$ dom-> loadHTML()需要html.你给它一个网址,你首先需要获得你要解析的页面的html.您可以使用file_get_contents().

我在我的图像抓取课中使用了这个.对我来说很好.

$html = file_get_contents('http://www.google.com/');
$dom = new domDocument;
$dom->loadHTML($html);
$dom->preserveWhiteSpace = false;
$images = $dom->getElementsByTagName('img');
foreach ($images as $image) {
  echo $image->getAttribute('src');
}
Run Code Online (Sandbox Code Playgroud)