fopen()和file_get_contents()打开URL获得网页内容的用法区别
来源:互联网 发布:python设计模式第二版 编辑:程序博客网 时间:2024/05/16 13:54
fopen()和file_get_contents()打开URL获得网页内容的用法区别
作者:admin 时间:2013-5-24 7:43:35在php里,要想打开网页URL获得网页内容,比较常用的函数是fopen()和file_get_contents()。如果要求不苛刻,此两个函数多数情况下是可以根据个人爱好任意选择的,本文谈下此两函数的用法有什么区别,以及使用时需要注意的问题。
fopen()打开URL
下面是一个使用fopen()打开URL的例子:
<?php
$fh = fopen('http://www.baidu.com/', 'r');
if($fh){
while(!feof($fh)) {
echo fgets($fh);
}
}
?>从此例子可以看到,fopen()打开网页后,返回的$fh不是字符串,不能直输出的,还需要用到fgets()这个函数来获取字符串。fgets()函数是从文件指针中读取一行。文件指针必须是有效的,必须指向由 fopen() 或 fsockopen() 成功打开的文件(并还未由 fclose() 关闭)。
可知,fopen()返回的只是一个资源,如果打开失败,本函数返回 FALSE 。
file_get_contents()打开URL
下面是一个使用file_get_contents()打开URL的例子:
<?php
$fh= file_get_contents('http://www.baidu.com/');
echo $fh;
?>从此例子看到,file_get_contents()打开网页后,返回的$fh是一个字符串,可以直接输出的。
通过上面两个例子的对比,可以看出使用file_get_contents()打开URL,也许是更多人的选择,因为其比fopen()更简单便捷。
不过,如果是读取比较大的资源,则是用fopen()比较合适。
知识扩充
file_get_contents()模拟referer,cookie, 使用proxy等等
参考代码
ini_set('default_socket_timeout',120);
ini_set('user_agent','MSIE 6.0;');
$context=array('http' => array ('header'=> 'Referer: http://www.baidu.com/', ),);
$xcontext = stream_context_create($context);
echo $str=file_get_contents('http://www.webkaka.com/',FALSE,$xcontext);导读:ini_set()的实例及用法
- fopen()和file_get_contents()打开URL获得网页内容的用法区别
- fopen()和file_get_contents()打开URL获得网页内容的用法区别
- fopen()和file_get_contents()打开URL获得网页内容的用法区别
- 抓网页内容file_get_contents curl fopen
- curl、fopen和file_get_contents区别
- curl、fopen和file_get_contents区别
- fopen,file_get_contents,curl的区别
- PHP中fopen,file_get_contents,curl函数的区别和性能
- php使用Url读取文件的内容及file_get_contents用法
- php fopen()和file_get_contents() 区别介绍
- php fopen,file_get_contents,curl的区别
- PHP中fopen,file_get_contents,curl的区别
- fopen、file_get_contents、curl区别
- file_get_contents()打开URL无法获得数据返回false原因
- php fopen file_get_contents curl区别
- [PHP]fopen、file_get_contents、curl区别
- PHP抓取外部资源函数fopen / file_get_contents / curl 的区别
- C中fopen打开方式r和rb的区别
- dede 获取当前栏目的上一级栏目名称,和链接
- MySQL Order By Rand()效率
- 织梦dedecms联动级别前台调用
- UCenter info: MySQL Query Error SQL:SELECT value FROM [Table]vars WHERE name=\'noteexists2′ Error:SELECT command denied to use
- ipone尺寸
- fopen()和file_get_contents()打开URL获得网页内容的用法区别
- 162. Find Peak Element
- dede调用全站的最新文章
- 关于APP,原生和H5开发技术的争论
- dede数据库类使用方法 $dsql
- 一个经典实用的PHP图像处理类
- dede 获取文章链接地址
- DedeCMS系统函数列表及用法详解
- HTML文件中也玩include文件包含