教程集 www.jiaochengji.com
教程集 >  脚本编程  >  php  >  正文 php使用fopen、curl获取网站及远程服务器信息的实例代码

php使用fopen、curl获取网站及远程服务器信息的实例代码

发布时间:2016-07-29   编辑:jiaochengji.com
本文介绍下,在php中,使用fopen、curl获取网站内容以及远程服务器信息的代码。有需要的朋友,作个参考吧。

例1,fopen获取网站内容。

<?php
/**
* 获取网站内容 fopen函数示例
* edit www.jbxue.com
*/
$handle = fopen ("http://www.jbxue.com/", "rb");
$contents = "";
while (!feof($handle)) {
$contents .= fread($handle, 8192);
}
fclose($handle);
echo $contents; //输出获取到得内容。
?>

代码2,

//适用于 PHP 5 及更高版本
<?php
$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
/**
* curl获取网站内容
*/
$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}");

有关wget的用法,大家可以参考如下的文章:
Linux的下载命令wget详解及例子
linux的wget命令详解
使用wget做站点镜像及wget的高级用法
linux下的下载利器wget的使用
wget下载文件时重命名的方法

不得不推荐下wget这个命令啊,那是相当的好用,建议大家牢固掌握。

下面说说,PHP抓取外部资源函数fopen / file_get_contents / curl 的区别:
fopen / file_get_contents 每次请求都会重新做DNS查询,并不对DNS信息进行缓存。
但是CURL会自动对DNS信息进行缓存。对同一域名下的网页或者图片的请求只需要一次DNS查询。如此便大大减少了DNS查询的次数。
因此,CURL的性能比fopen / file_get_contents要好很多。

有了以上的分析,在用php获取网站内容时,对这几个函数如何取舍,你现在的思路是否清晰很多呢?!

您可能感兴趣的文章:
php使用fopen、curl获取网站及远程服务器信息的实例代码
PHP获取远程网页内容(fopen,curl方式)
PHP fopen/file_get_contents与curl性能比较
PHP 获取远程网页内容的代码
failed to open stream: HTTP request failed
php 获取远程网页内容简单函数
php读取远程文件的三种方法分享
php中curl、fsocket、file_get_content函数比较
php curl参数详解与用法大全
php file_get_contents函数抓取页面信息的代码

关键词: curl  fopen  服务器信息   
[关闭]
~ ~