在 PHP 中使用定界符拆分 200 MB 文本文件
Split 200MB textfile with delimiter-line in PHP
我需要将一个大的文本文件 (200MB) 拆分成多个较小的文件。拆分应基于定义的文本行。
大文件
This is a title
Lorem Ipsum
New Chapter
This is a title
Lorem Ipsum
所以行This is a title
应该标记文件的分割位置,它也应该是新文件的第一行。所以结果将是:
第一个文件
This is a title
Lorem Ipsum
New Chapter
第二个文件
This is a title
Lorem Ipsum
我可以将文本文件拆分为定义的字节大小,但这不是我需要的:
$i = 1;
$fp = fopen("big_file.txt",'r');
while(! feof($fp)) {
$contents = fread($fp,1000);
file_put_contents($i.'.txt',$contents);
$i++;
}
我需要拆分定义的行。
逐行搜索分隔符:
$i = 1;
$file = fopen("big_file.txt", "r");
while(!feof($file)){
$line = fgets($file);
if ($line == "delimiter") {
if ($contents) file_put_contents($i.'.txt',$contents);
$contents = '';
$i++;
}
else $contents .= $contents;
}
fclose($file);
我需要将一个大的文本文件 (200MB) 拆分成多个较小的文件。拆分应基于定义的文本行。
大文件
This is a title
Lorem Ipsum
New Chapter
This is a title
Lorem Ipsum
所以行This is a title
应该标记文件的分割位置,它也应该是新文件的第一行。所以结果将是:
第一个文件
This is a title
Lorem Ipsum
New Chapter
第二个文件
This is a title
Lorem Ipsum
我可以将文本文件拆分为定义的字节大小,但这不是我需要的:
$i = 1;
$fp = fopen("big_file.txt",'r');
while(! feof($fp)) {
$contents = fread($fp,1000);
file_put_contents($i.'.txt',$contents);
$i++;
}
我需要拆分定义的行。
逐行搜索分隔符:
$i = 1;
$file = fopen("big_file.txt", "r");
while(!feof($file)){
$line = fgets($file);
if ($line == "delimiter") {
if ($contents) file_put_contents($i.'.txt',$contents);
$contents = '';
$i++;
}
else $contents .= $contents;
}
fclose($file);