php 如何在有限的内存中读取大文件

时间:2023-03-10 04:13:55
php 如何在有限的内存中读取大文件

突然遇到了一个要读取超过80M文件的需求,很悲剧的,不管是file_get_content还是file什么的,都会将读取的文件一次性加载到内存中。

正常情况下,我们可以使用fseek来读取,好处就是不会一次性读取,以下代码只适合边取边处理的情况,不适合一次性读取一次性处理。

可以用以下办法生成测试文件

$file_handle = fopen("./****.txt", "rb+");
for ($index1 = 1; $index1 <= 2000000; $index1++) {
fwrite($file_handle, 'http://blog.****.net/longxuu/article/details/'.$index1."\r");
}
fclose($file_handle);

读取处理代码如下:

$i = 0;
$now = '';
while ($i >= 0) {
if ($i>10) {
break;
}
fseek($file_handle, 0, SEEK_CUR);
$now = fgetc($file_handle);//可以自己写个判断false表示文件到头
if ($now == "\r") {
echo '找到断点';
}
echo $now;
$i++;
}
fclose($file_handle);

相关文章