PHP中file()和file_get_contents()的区别(转)
2013-12-04 15:20
260 查看
PHP中file() 函数和file_get_contents() 函数的作用都是将整个文件读入某个介质,其主要区别就在于这个介质的不同。file() 函数是将文件读入一个数组中,而file_get_contents()是将文件读入一个字符串中。
file() 函数是把整个文件读入一个数组中,然后将文件作为一个数组返回。数组中的每个单元都是文件中相应的一行,包括换行符在内。如果失败,则返回 false。
file_get_contents() 函数是把整个文件读入一个字符串中。和 file() 一样,不同的是file_get_contents() 把文件读入一个字符串。file_get_contents() 函数是用于将文件的内容读入到一个字符串中的首选方法。如果操作系统支持,还会使用内存映射技术来增强性能。
我们来看一个例子吧,下面是test.txt的内容如下:
file_get_contents的操作方法如下:
file的操作方法如下:
效果与上面完全相同的,结果如下:
file()与file_get_contents()得到文件的内容方式是直接得到。这个与fgets不一样,fgets得到的文件内容方式是由fopen打开的资源流。
在可以用file_get_contents替代file、fopen、feof、fgets等系列方法的情况下,尽量用 file_get_contents,因为他的效率高得多!但是要注意file_get_contents在打开一个url文件时候的php版本问题。
file() 函数是把整个文件读入一个数组中,然后将文件作为一个数组返回。数组中的每个单元都是文件中相应的一行,包括换行符在内。如果失败,则返回 false。
file_get_contents() 函数是把整个文件读入一个字符串中。和 file() 一样,不同的是file_get_contents() 把文件读入一个字符串。file_get_contents() 函数是用于将文件的内容读入到一个字符串中的首选方法。如果操作系统支持,还会使用内存映射技术来增强性能。
我们来看一个例子吧,下面是test.txt的内容如下:
springload news eightnight
file_get_contents的操作方法如下:
$content = file_get_contents('test.txt'); $temp =str_replace(chr(13),'|',$content); $arr =explode('|',$temp); print_r($arr);
file的操作方法如下:
print_r(file('test.txt'));
效果与上面完全相同的,结果如下:
Array ( [0] => springload [1] => news [2] => eightnight )
file()与file_get_contents()得到文件的内容方式是直接得到。这个与fgets不一样,fgets得到的文件内容方式是由fopen打开的资源流。
在可以用file_get_contents替代file、fopen、feof、fgets等系列方法的情况下,尽量用 file_get_contents,因为他的效率高得多!但是要注意file_get_contents在打开一个url文件时候的php版本问题。
相关文章推荐
- PHP中fopen,file_get_contents,curl的区别
- php fopen,file_get_contents,curl的区别
- php fopen与file_get_contents的区别
- php fopen()和file_get_contents() 区别介绍
- PHP中fopen,file_get_contents,curl函数的区别
- PHP中fopen,file_get_contents,curl函数的区别和性能
- PHP中fopen,file_get_contents,curl函数的区别
- PHP中file() 函数和file_get_contents() 函数的区别
- PHP-CGI 进程 CPU 100% 与 file_get_contents 函数的关系
- file_get_contents("php://input")的使用方法
- file_get_contents("php://input")的使用方法
- PHP写日志fwrite和file_put_contents的区别与性能
- PHP中用file_get_contents抓取网页
- PHP-CGI 进程 CPU 100% 与 file_get_contents 函数的关系
- php程序突然不能用file_get_contents()访问远程网址了?
- file_get_contents("php://input");
- php中 curl, fsockopen ,file_get_contents 三个函数
- php获取输入流 file_get_contents('php://input')
- php获取本地图片直接输出浏览器,file_get_contents
- PHP中使用file_get_contents()抓取网页乱码的问题