php - 为什么我在这里没有取回任何图像?

标签 php domdocument

$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/

相关文章:

php - 使用 PHP 关闭服务器

php - 要包含必需的curl header 吗?

php - 当在 joomla 中删除上传的文件时,从 id 数组中删除上传的文件吗?

php - 使用 DOMDocument 和 DOMXPath 如何忽略匹配的某些字符?

java - 如何在“with\”转义时避免转义 &

PHP nodeValue 剥离 html 标签 - innerHTML 替代方案?

php - Laravel TestCase 不发送授权 header (JWT token )

php - cUrl 打开多个 URL

php - 使用 PHP 获取 DOM 元素字符串

php - 如何在不添加空格的情况下使用 PHP DOMDocument saveHTML($node)?