袁来如此的工作笔记
袁来如此的工作笔记
竹杖芒鞋轻胜马,谁怕? 一蓑烟雨任平生。

大文件,PHP咋按行读取

浏览量:125

正确方法是不能够使用 file_get_contents 函数,一股脑把所有文件内容扔到内存的。应该使用 fgets 函数逐行读取:

$handle = fopen("inputfile.txt", "r"); if ($handle) {while (($line = fgets($handle)) !== false) { // process the line read. } fclose($handle); } else { // error opening the file. }


首先打开文件句柄,然后逐行使用 fgets 读取,处理完毕后使用 fclose 显式关闭。

当然,你也可以不必使用 false 判断,转而使用 feof 检测是否到文件末尾即可:

if ($file = fopen("file.txt", "r")) {while(!feof($file)) { $line = fgets($file); # do same stuff with the $line }fclose($file);}

所谓“条条大道通罗马”,实现功能的方法不止一种。我们更推荐的是下面的这种写法。使用 PHP 5.1 之后提供的 SplFileObject 对象处理文件。

那么就可以这样写:

$file = new SplFileObject("file.txt");// Loop until we reach the end of the file. while (!$file->eof()) { // Echo one line from the file. echo $file->fgets(); } // Unset the file to call __destruct(), closing the file handle. $file = null;

打赏