Php script to split large files to smaller files

This article will describe how you can split large php files line by line to smaller php files.

If you have a large php file with content in each line of the file and you would like to convert it to smaller chunks then here you will find the php script code to do that.

Let us suppose that you have a big php files with content over 100,000 lines and you would like to convert it to smaller files with say 500 lines each then the script to do that is as follows

// converting 100,000 lines content to csv files with 500 lines content in each each file
$file = fopen("raw.txt","r"); // this file could be raw.log or anything
//file will be split into new file chunks of 500 lines in each file
//files will be named List-1.txt ,list-2.txt....
$max_lines = 500; //change as per your requirement
while(! feof($file))
      //create the new file with new name dynamically
      $myfile = fopen("List-".$list_count.".txt", "a") ;
      echo "<br><br><b>Created and Opened File : </b>List-".$list_count.".txt"."<br>";
      while($count <= $max_lines){
         $line = fgets($file);
         $content = trim($line);
         fwrite($myfile, $content.",");
         //fwrite ($myfile, $content."\n"); //uncomment this and comment previous line
         //if you would like content to appear in new lines
         echo "<br>Added : ".$count.". ".$content." to file : List-".$list_count ;

To run this php code you will need a php installation locally (such as Xampp) or on a server.

That is all.

If you liked this article please do leave a reply and share it with friends.


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.