fwrite - Write each 200 lines to new file in PHP -


my code:

$file = "read_file.txt"; $file_path =  "write.txt"; $count = 0; $counter = 1;  $lines = file($file); foreach ($lines $line) { if($count == 200){    $file_path =  "write_".$counter++."txt";    $count == 0; }    $count++;    $file_handle = fopen($file_path, "w");    $file_contents = $line;    fwrite($file_handle, $file_contents);    fclose($file_handle); } 

i want write every new 200 lines read file new files (in other words divide whole file 200lines/file) everytime 1 line new file can me out im doing wrong

you opening new file each line overwrites last why getting 1 line per file. not way want to.

instead, loop through , groups of 200 lines, , write. means 1001 line file have 6 writes, instead of 1001. way much faster other methods

$count = 0; $counter = 1; $file_lines = '';  $lines = file("read_file.txt"); foreach ($lines $line) {    $file_lines .= $line . "\n";    $count++;    if($count == 200) {       $file_handle = fopen("write_".$counter++."txt", "w+");       fwrite($file_handle, $file_lines);       fclose($file_handle);              $count = 0;       $file_lines = '';    } } 

edit: darren's suggestion array_chunk better variable length arrays


Comments

Popular posts from this blog

toolbar - How to add link to user registration inside toobar in admin joomla 3 custom component -

linux - disk space limitation when creating war file -

How to provide Authorization & Authentication using Asp.net, C#? -