复制代码 代码如下:
<?php
$handle = fopen ("http://s.jb51.net/", "rb");
$contents = "";
while (!feof($handle)) {
$contents .= fread($handle, 8192);
}
fclose($handle);
echo $contents; //输出获取到得内容。
?>
复制代码 代码如下:
// 对 php 5 及更高版本可以使用下面的代码
<?php
$handle = fopen("http://s.jb51.net", "rb");
$contents = stream_get_contents($handle);
fclose($handle);
echo $contents;
?>
但上面的代码容易出现 failed to open stream: http request failed!错误,解决方法
有人说在php.ini中,有这样两个选项:allow_url_fopen =on(表示可以通过url打开远程文件),user_agent="php"(表示通过哪种脚本访问网络,默认前面有个 " ; " 去掉即可。)重启服务器。
但是有些还是会有这个警告信息,想用完美的解决还差一步,还得设置php.ini里面的user_agent,php默认的user_agent是php,我们把它改成mozilla/4.0 (compatible; msie 6.0; windows nt 5.0)来模拟浏览器就可以了
user_agent="mozilla/4.0 (compatible; msie 6.0; windows nt 5.0)"
在工作中遇到这个问题,后完美解决,故分享给大家。
2、通过curl来实现
复制代码 代码如下:
<?php
$url = "http://s.jb51.net";
$ch = curl_init();
curl_setopt ($ch, curlopt_url, $url);
curl_setopt ($ch, curlopt_returntransfer, 1);
curl_setopt ($ch, curlopt_connecttimeout,10);
$dxycontent = curl_exec($ch);
echo $dxycontent;
?>
linux下可以使用下面的代码下载
exec("wget {$url}");
php抓取外部资源函数fopen / file_get_contents / curl 的区别
fopen / file_get_contents 每次请求都会重新做dns查询,并不对dns信息进行缓存。
但是curl会自动对dns信息进行缓存。对同一域名下的网页或者图片的请求只需要一次dns查询。
这大大减少了dns查询的次数。
所以curl的性能比fopen / file_get_contents 好很多。
硕编程原创内容,转载请注明出处。
【说明】:本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!