Reputation: 1657
I need to split a big text-file (200MB) into multiple smaller files. The split should be based on a defined text-line.
Big file
This is a title
Lorem Ipsum
New Chapter
This is a title
Lorem Ipsum
So the line This is a title
should mark where to split the file and it also should be the first line of the new file. So the result would be:
First file
This is a title
Lorem Ipsum
New Chapter
Second file
This is a title
Lorem Ipsum
I can split the textfile into defined byte-sizes, but this is not, what I need:
$i = 1;
$fp = fopen("big_file.txt",'r');
while(! feof($fp)) {
$contents = fread($fp,1000);
file_put_contents($i.'.txt',$contents);
$i++;
}
I need to split for a defined line.
Upvotes: 0
Views: 113
Reputation: 17332
Just go line by line and search for the delimiter:
$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);
Upvotes: 1