Split a text file in PHP
php, string, text-processing
Solution
You should be able to accomplish this easily with a basic fread(). You can specify how many bytes you want to read, so it's trivial to read in an exact amount and output it to a new file.
Try something like this:
$i = 1;
$fp = fopen("test.txt",'r');
while(! feof($fp)) {
$contents = fread($fp,1000);
file_put_contents('new_file_'.$i.'.txt',$contents);
$i++;
}
EDIT
If you wish to stop after a certain amount of length OR on a certain character, then you could use stream_get_line() instead of `fread()`. It's almost identical, except it allows you to specify any ending delimiter you wish. Note that it does not return the delimeter as part of the read.
$contents = stream_get_line($fp,1000,".");
Problem
How can I split a large text file into separate files by character count using PHP? So a 10,000 character file split every 1000 characters would be split into 10 files. Further, can I split only after a full stop is found? Thanks. UPDATE 1: I like zombats code and I removed some errors and have come up with the following, but does anyone know how to only split after a full stop? ``` $i = 1; $fp = fopen("test.txt", "r"); while(! feof($fp)) { $contents = fread($fp,1000); file_put_contents('new_file_'.$i.'.txt', $contents); $i++; } ``` UPDATE 2: I took zombats suggestion and modified the code to that below and it seems to work - ``` $i = 1; $fp = fopen("test.txt", "r"); while(! feof($fp)) { $contents = fread($fp,20000); $contents .= stream_get_line($fp,1000,"."); $contents .="."; file_put_contents("Split/".$tname."/"."new_file_".$i.".txt", $contents); $i++; } ```