如果行以 0x0A 分隔,如何在 PHP 中逐行读取文件?
How to read a file line by line in PHP if lines are separated with 0x0A?
我们有一个 8 GB 的文件,每一行都是一个 serialize()
输出,因此它可以包含二进制数据。但我注意到数据不包含 0x0A
字节,该字节用于分隔文件中的行。
函数 fgets()
没有帮助,因为它检测 0x0A
或 0x0D
字节的行尾,所以 fgets()
看到更多的行分隔符比存在。
是否有 fgets()
版本仅使用 0x0A
字节作为我的案例的行分隔符?
是否有另一种方法无需编写我自己的读取缓冲解析行发射解决方案?
P.S. file_get_contents()
不喜欢大于 2GB 的文件。
你或许可以试试:
string stream_get_line ( resource $handle , int $length [, string $ending ] );
//i.e.
string stream_get_line ($handle , filesize($myFile) , '\n' );
解决方案
我目前的解决方案是基于用户 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 );
我们有一个 8 GB 的文件,每一行都是一个 serialize()
输出,因此它可以包含二进制数据。但我注意到数据不包含 0x0A
字节,该字节用于分隔文件中的行。
函数 fgets()
没有帮助,因为它检测 0x0A
或 0x0D
字节的行尾,所以 fgets()
看到更多的行分隔符比存在。
是否有 fgets()
版本仅使用 0x0A
字节作为我的案例的行分隔符?
是否有另一种方法无需编写我自己的读取缓冲解析行发射解决方案?
P.S. file_get_contents()
不喜欢大于 2GB 的文件。
你或许可以试试:
string stream_get_line ( resource $handle , int $length [, string $ending ] );
//i.e.
string stream_get_line ($handle , filesize($myFile) , '\n' );
解决方案
我目前的解决方案是基于用户 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 );