$url = 'http://www.w3schools.com/js/js_loop_for.asp';
$html = @file_get_contents($url);
$doc = new DOMDocument();
@$doc->loadHTML($html);
$xml = @simplexml_import_dom($doc);
$images = $xml->xpath('//img');
var_dump($images);
die();
输出是:
array(0) { }
但是,在页面源代码中我看到了这个:
<img border="0" width="336" height="69" src="/images/w3schoolslogo.gif" alt="W3Schools.com" style="margin-top:5px;" />
编辑:它出现$html
的内容停止在 <body>
此页面的标记。知道为什么吗?
最佳答案
It appears $html's contents stop at the tag for this page. Any idea why?
是的,您必须为该页面提供有效的用户代理。
$url = 'http://www.w3schools.com/js/js_loop_for.asp';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERAGENT, "MozillaXYZ/1.0");
curl_exec($ch);
输出所有内容到结尾 </html>
包括您要求的 <img border="0" width="336" height="69" src="/images/w3schoolslogo.gif" alt="W3Schools.com" style="margin-top:5px;" />
当没有用户代理的简单 wget 或 curl 仅返回到 <body>
标签。
$url = 'http://www.w3schools.com/js/js_loop_for.asp';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERAGENT, "MozillaXYZ/1.0");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$html = curl_exec($ch);
$doc = new DOMDocument();
$doc->loadHTML($html);
$xml = simplexml_import_dom($doc);
$images = $xml->xpath('//img');
var_dump($images);
die();
编辑: 我的第一篇文章指出 xpath 仍然存在问题...我只是没有尽职调查,上面更新的代码运行良好。我忘记强制 curl 输出到字符串而不是打印到屏幕(默认情况下是这样)。
关于php - 为什么我在这里没有取回任何图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5719328/