如果用0x0A分隔行,如何在 PHP 中逐行读取文件


How to read a file line by line in PHP if lines are separated with 0x0A?

我们有一个 8 GB 的文件,每行都是一个serialize()输出,所以它可以包含二进制数据。但我注意到数据不包含0x0A字节,该字节用于分隔文件中的行。

函数fgets()没有帮助,因为它检测0x0A0x0D字节上的行尾,因此fgets()看到的行分隔符比存在的多。

是否有仅使用 0x0A 字节作为我的情况的行分隔符的fgets()版本?

有没有另一种方法不编写我自己的读取-缓冲-解析-行-发射解决方案?

附言 file_get_contents()不喜欢大于 2GB 的文件。

你可以试试:

string stream_get_line ( resource $handle , int $length [, string $ending ] );
//i.e.
string stream_get_line ($handle , filesize($myFile) , ''n' );

参考: http://php.net/manual/en/function.stream-get-line.php

解决方案

我目前的解决方案是基于用户Jonid Bendo的评论: stream_get_line() ( http://php.net/manual/en/function.stream-get-line.php ),但在我的平台上,stream_get_line() 不会返回超过 8192 字节的行,所以我使用一个循环来检测它并重建更长的字符串:

$master = "";
do
{
    $line = stream_get_line ($handle, 1024*128, "'n");
    $ll = strlen($line);
    if ($ll < 1) {
        break;
    }
    $badline = ($ll == 8192) && (''n' != $line[$ll-1]);
    $master .= $line;
} while( $badline );