本文翻译自:How to read a large file line by line?
I want to read a file line by line, but without completely loading it in memory. 我想逐行读取文件,但没有将其完全加载到内存中。
My file is too large to open in memory, and if try to do so I always get out of memory errors. 我的文件太大,无法在内存中打开,如果尝试这样做,我总是会走出内存错误。
The file size is 1 GB. 文件大小为1 GB。
#1楼
参考:https://stackoom.com/question/ta2n/如何逐行读取大文件
#2楼
You can use the fgets()
function to read the file line by line: 您可以使用fgets()
函数逐行读取文件:
$handle = fopen("inputfile.txt", "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
// process the line read.
}
fclose($handle);
} else {
// error opening the file.
}
#3楼
if ($file = fopen("file.txt", "r")) {
while(!feof($file)) {
$line = fgets($file);
# do same stuff with the $line
}
fclose($file);
}
#4楼
Use buffering techniques to read the file. 使用缓冲技术读取文件。
$filename = "test.txt";
$source_file = fopen( $filename, "r" ) or die("Couldn't open $filename");
while (!feof($source_file)) {
$buffer = fread($source_file, 4096); // use a buffer of 4KB
$buffer = str_replace($old,$new,$buffer);
///
}
#5楼
小心'while(!feof ... fgets()'东西,fgets可能会出错(返回false)并永远循环,而不会到达文件末尾。codaddict最接近正确,但是当您的“ while fgets”时循环结束,检查feof;如果不正确,则错误。
#6楼
Function to Read with array return 读取数组返回的函数
function read_file($filename = ''){
$buffer = array();
$source_file = fopen( $filename, "r" ) or die("Couldn't open $filename");
while (!feof($source_file)) {
$buffer[] = fread($source_file, 4096); // use a buffer of 4KB
}
return $buffer;
}