PHP 获取远程网页内容的代码
本文介绍下,
php 实现的获取远程网页内容的几个方法,包括 fopen、curl 方式,有需要的朋
友参考下吧。
分享几段获取远程网页内容的
php 代码。
1、fopen 方式
<?php
$handle = fopen ("http://www.jbxue.com/", "rb");
$contents = "";
while (!feof($handle)) {
$contents .= fread($handle, 8192);
}
fclose($handle);
echo $contents; //
输出获取到得内容。
//以下适用于 php5
以上版本
$handle = fopen("http://www.jbxue.com", "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://www.jbxue.com";
$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 的区别: