Heim  >  Artikel  >  php教程  >  PHP使用fopen与file_get_contents读取文件实例分享,

PHP使用fopen与file_get_contents读取文件实例分享,

WBOY
WBOYOriginal
2016-06-13 08:45:12824Durchsuche

PHP使用fopen与file_get_contents读取文件实例分享,

php中读取文件可以使用fopen和file_get_contents这两个函数,二者之间没有本质区别,只是前者读取文件的php代码相比后者要复杂一点。本文章通过实例向大家讲解fopen和file_get_contents读取文件的实现代码。需要的码农可以参考一下。

fopen读取文件的代码如下:

<&#63;php
$file_name = "1.txt";
echo $file_name . "
";
$fp = fopen($file_name, 'r');
//$buffer=fgets($fp);
while (!feof($fp)) {
$buffer = fgets($fp);
echo $buffer;
}
fclose($fp);
&#63;> 

注意fopen读取文件需要配合使用fgets和fclose函数。

file_get_contents读取文件的代码如下:

<&#63;php
if (file_exists($path)) {
$body = file_get_contents($path);
echo $body; //输入文件内容
} else {
echo "文件不存在 $path";
}
&#63;> 

这个函数是一次性读取所有文件内容并显示出来,但是如果文件超大会导致php占很大的内存了。

当然还有像file这种一般是把文件读成数组了,同时也可以实现读取文件了

下面给大家介绍下fopen()和file_get_contents()打开URL获得网页内容的用法区别

在php里,要想打开网页URL获得网页内容,比较常用的函数是fopen()和file_get_contents()。如果要求不苛刻,此两个函数多数情况下是可以根据个人爱好任意选择的,本文谈下此两函数的用法有什么区别,以及使用时需要注意的问题。

fopen()打开URL

下面是一个使用fopen()打开URL的例子:

<&#63;php
$fh = fopen('http://www.baidu.com/', 'r');
if($fh){
while(!feof($fh)) {
echo fgets($fh);
}
}
&#63;>

从此例子可以看到,fopen()打开网页后,返回的$fh不是字符串,不能直输出的,还需要用到fgets()这个函数来获取字符串。fgets()函数是从文件指针中读取一行。文件指针必须是有效的,必须指向由 fopen() 或 fsockopen() 成功打开的文件(并还未由 fclose() 关闭)。

可知,fopen()返回的只是一个资源,如果打开失败,本函数返回 FALSE 。

file_get_contents()打开URL

下面是一个使用file_get_contents()打开URL的例子:

<&#63;php
$fh= file_get_contents('http://www.baidu.com/');
echo $fh;
&#63;>

从此例子看到,file_get_contents()打开网页后,返回的$fh是一个字符串,可以直接输出的。

通过上面两个例子的对比,可以看出使用file_get_contents()打开URL,也许是更多人的选择,因为其比fopen()更简单便捷。

不过,如果是读取比较大的资源,则是用fopen()比较合适。

您可能感兴趣的文章:

  • PHP-CGI进程CPU 100% 与 file_get_contents 函数的关系分析
  • 深入php函数file_get_contents超时处理的方法详解
  • 解析PHP中的file_get_contents获取远程页面乱码的问题
  • file_get_contents("php://input", "r")实例介绍
  • php读取本地文件常用函数(fopen与file_get_contents)
  • PHP file_get_contents设置超时处理方法
  • php 使用file_get_contents读取大文件的方法
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn