Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a text file in PHP

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++;
    }
like image 811
usertest Avatar asked Mar 27 '26 22:03

usertest


2 Answers

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,".");
like image 70
zombat Avatar answered Mar 31 '26 06:03

zombat


There is a bug in run function; variable $split not defined.

like image 39
ABC Avatar answered Mar 31 '26 04:03

ABC