strago Posted February 18, 2010 Share Posted February 18, 2010 $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 More sharing options...
Catfish Posted February 18, 2010 Share Posted February 18, 2010 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. Link to comment https://forums.phpfreaks.com/topic/192483-remove-last-line-of-text-file/#findComment-1014216 Share on other sites More sharing options...
salathe Posted February 18, 2010 Share Posted February 18, 2010 Or you could just remove the last line from the $lines array with array_pop Link to comment https://forums.phpfreaks.com/topic/192483-remove-last-line-of-text-file/#findComment-1014269 Share on other sites More sharing options...
strago Posted February 18, 2010 Author Share Posted February 18, 2010 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. Link to comment https://forums.phpfreaks.com/topic/192483-remove-last-line-of-text-file/#findComment-1014418 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.