Jump to content

Remove last line of text file.


strago

Recommended Posts

$lines = file('/public_html/downloads.txt');
$fopen = fopen("/public_html/downloads.txt", "w+");
fwrite( $fopen, "This goes in file as top line.\r\n");
foreach ($lines as $line)
{
fwrite( $fopen, "$line");
}
fclose($fopen);

 

This adds data to a text file, as the first line. How do I make it then delete the bottom last line in the file?

Link to comment
https://forums.phpfreaks.com/topic/192483-remove-last-line-of-text-file/
Share on other sites

modify your code to be:

$lines = file('/public_html/downloads.txt');
$fopen = fopen("/public_html/downloads.txt", "w+");
fwrite( $fopen, "This goes in file as top line.\r\n");
$i = 0;
foreach ($lines as $line)
{
   if ($i != count($lines))   // if counter _doesn't_ equal the number of lines in the array (number of lines in old file)
         fwrite($fopen, "$line"); // write line to the file, else do nothing (do not write the current line to file)
   $i++;
}

 

Untested. you may need to double check it.

Thanks

 

array_pop($lines);
$file = join('',$lines);

 

did it.

 

$lines = file('/public_html/downloads.txt');
array_pop($lines);
$file = join('',$lines);
$fopen = fopen("/public_html/downloads.txt", "w+");
fwrite( $fopen, "This goes in file as top line.\r\n");
foreach ($lines as $line)
{
fwrite( $fopen, "$line");
}
fclose($fopen);

 

I had tried array_pop but I think I had it in the wrong spot.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.