大文件,PHP咋按行读取
浏览量:125
$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;


感谢支持与鼓励~