PHP中file() 函数和file_get_contents() 函数的区别

PHP中file() 函数和file_get_contents() 函数的作用都是将整个文件读入某个介质,其主要区别就在于这个介质的不同。

file() 函数是把整个文件读入一个数组中,然后将文件作为一个数组返回。数组中的每个单元都是文件中相应的一行,包括换行符在内。如果失败,则返回 false。

file_get_contents() 函数是把整个文件读入一个字符串中。和 file() 一样,不同的是 file_get_contents() 把文件读入一个字符串。file_get_contents() 函数是用于将文件的内容读入到一个字符串中的首选方法。如果操作系统支持,还会使用内存映射技术来增强性能。

例如,我们这里有一txt文档,如果使用file()函数,代码如下:<?php print_r(file(”test.txt”)); ?>,那么浏览器会输出:

Array ( [0] => Hello Realure. [1] => If not now,when?! [2] => If not me,who?! )

如果使用file_get_contents() 函数,代码如下:<?php print_r(file_get_contents(”test.txt”)); ?>,那么浏览器会输出:

Hello Realure. If not now,when?! If not me,who?!

相关文章: 

If you enjoyed this post, please consider to leave a comment or subscribe to the feed and get future articles delivered to your feed reader.

Comments

还没有评论。

发表评论

(必填)

(必填)