如何逐行读取大文件?

24 浏览
0 Comments

如何逐行读取大文件?

我想逐行读取一个文件,但不要完全加载到内存中。

我的文件太大,无法在内存中打开,如果尝试这样做,我总是会出现内存不足错误。

文件大小为1 GB。

admin 更改状态以发布 2023年5月20日
0
0 Comments
if ($file = fopen("file.txt", "r")) {
    while(!feof($file)) {
        $line = fgets($file);
        # do same stuff with the $line
    }
    fclose($file);
}

翻译成为:包含123的段落。

0
0 Comments

您可以使用fgets()函数逐行读取文件:

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

0