append every n lines in a file PHP

Ask about general coding issues or problems here.

Moderators: egami, macek, gesf

Post Reply
New php-forum User
New php-forum User
Posts: 2
Joined: Fri Jun 15, 2018 11:36 am

Sun Jun 17, 2018 7:18 am

Hi Team,

I have a PHP where a user enters a number($num) in a textfield. The program counts the number of lines from largefile.txt($lines). I want the the program to read every $num lines from largefile.txt and append them to $lines/$num files(for example, if the file containes 8 records and $num is 2, 4 files will be created each with $num(2) records).

<h2>HTML Forms</h2>
<form action="/bank/bank.php" method="post">
<input type="text" name="number" maxlength=50 >
<input type="submit" name="formSubmit" value="Submit">
if( isset($_POST['formSubmit'])=="Submit") //use isset else Undefined index:
$num = $_POST['number'];

// The code below counts the total number of lines in the file
echo $num;
$file = "largefile.txt";
$lines = count(file($file));
echo "There are $lines lines in $file <br/>";

The code below loops each line in the "largefile.txt" and creates and appends to new files. The issue is how do I append every $num to new files?
$file = fopen("largefile.txt","r");
$count = "1";
while(! feof($file))
while($count<= $lines){

//code below creates 'count' files and appends entries to it
$myfile = fopen("newfile$count.txt", "w") or die("Unable to open file!");
fwrite($myfile, fgets($file));
echo "The number is: $count <br>";


php-forum Fan User
php-forum Fan User
Posts: 584
Joined: Fri Apr 01, 2016 2:18 am

Mon Jun 18, 2018 9:29 pm

while walking over the data you can check every key with the modulo operator.

Post Reply