在 php 中读取大型多 GB 大小的文本文件

Reading a big multi GB size text file in php

我有一个 197gb 的文本文件,我想读取并将其内容推送到 MySql 数据库中。我知道,我不能把那个大文件放在 PHP 缓冲区中并整体读取它,所以我想一次读取几百行并继续读取下一个和下一个以读取整个文件。

我正在用这个尝试,但是页面 returns 什么都没有

<?php
$i = 0;
$handle = fopen("./data/200gbfile.txt", "r") or die("Couldn't get handle");
if ($handle) {
    while (($line = fgets($handle)) !== false) {
        echo $line . "<br />";
        if ($i > 100) {
            exit;
        }
        $i++;
    }
    fclose($handle);
} else {
    echo "Error Opeing File!";
}
?>

php 设置中是否有要处理的最大文件大小限制?

EDIT: for the 197gb file in question, fopen is failing to return anything and the output page is just going blank.

您可以使用 ini_set('memory_limit','16M'); 来设置大小,但我不知道它是否能处理这么大的文件。从未测试过..

您可以分块读取文件以节省内存:

例如:

$fd = @fopen("./data/200gbfile.txt", "r");

while (!feof($fd)) {
   $data = fread($fd, 1024); // read the file in 1024kb chunks
   // handle current data (read line by line for example)
}
fclose($fd);

但不知道这是否适用于 100GB+ 的文件。

Edit: @ with fopen is required as suggested by Roman.