首先我们来看一下fopen()与file()读取文件的代码:

1.fopen()函数打开文件或者 URL,然后使用fgets按行读取文件

$handle = fopen(\"/tmp/uploadfile.txt\", \"r\") or die(\"Couldn\'t get handle\");
if ($handle) {
    while (!feof($handle)) {
        $buffer = fgets($handle, 4096);
        // Process buffer here..
        /*  http://www.manongjc.com/article/1418.html */
    }
    fclose($handle);
}

 

2.file() 函数把整个文件读入一个数组中

$array = file(\'/path/to/text.txt\');

 

下面我们来分析fopen()与file()读取大文件的效率:

分别使用fopen()与file()读取两个文件,一个是1.3GB的文件,一个是9.5G的文件;结果如下:

1.3G文件所消耗的时间:

  1. fopen()读取文件消耗169ms 
  2. file() 读取文件消耗4469ms

9.5GB所消耗的时间:

  1. fopen()读取文件消耗2532ms
  2. file()读取文件消耗7998ms

由此可知:在读取大文件的时候,file()函数比fopen函数更快,效率更高。

收藏 打印