如何逐行读取大文件


如何在PHP中逐行读取文件,而不将其完全加载到内存中?

我的文件太大,无法在内存中打开,所以我总是有内存耗尽错误。

文件大小为1 GB。

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

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

    fclose($handle);
} else {
    // error opening the file.
} 

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

未经作者同意,本文严禁转载,违者必究!