PHP 一行一行读取超大文本文件的内容

Php 2021-03-14 阅读 186 评论 0

以下列出在 PHP 中一行行读取文本的几种方法。

1. 使用 file 方法

参考 file 方法,该方法把整个文件读入一个数组中,数组的每个元素对应于文件中的一行(结尾会附加换行符)。对于小文件,使用这个方法最方便不过了。但是有时候需要读取几百M,甚至几 G 的文件,比如日志等,可能会出现内存限制,可以使用第 2、3方法。

$lines = file('test.txt');
// 循环遍历数组
foreach ($lines as $line) {
    var_dump($line);
}

输出如下,可以看到每一行最后会有一个换行符:

/test.php:6:
string(9) "line one
"
/test.php:6:
string(9) "line two
"
/test.php:6:
string(11) "line three
"

2. 使用 fgets 方法

参考 fgets 方法,对于此方法的第 2 个参数,不指定大小,将返回整行的数据。

$handle = fopen("./test.txt", "r");
if ($handle) {
    while (($buffer = fgets($handle)) !== false) {
        var_dump($buffer);
    }
    if (!feof($handle)) {
        echo "Error: unexpected fgets() fail\n";
    }
    fclose($handle);
}

3. 使用 SplFileObject

参考 splfileobject 文件对象,使用 fgets 方法 获取文件行,与第 2 种方法有相似之处。

$file = new SplFileObject("test.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;
最后更新 2021-03-14