How can I remove the last line of a file using php?
I created a function to remove x number of lines from the bottom. Set $max
to the number of lines you want to delete.
function trim_lines($path, $max) {
// Read the lines into an array
$lines = file($path);
// Setup counter for loop
$counter = 0;
while($counter < $max) {
// array_pop removes the last element from an array
array_pop($lines);
// Increment the counter
$counter++;
} // End loop
// Write the trimmed lines to the file
file_put_contents($path, implode('', $lines));
}
Call the function like this:
trim_lines("filename.txt", 1);
The variable $path
can be a path to the file or a filename.
This should works :
<?php
// load the data and delete the line from the array
$lines = file('filename.txt');
$last = sizeof($lines) - 1 ;
unset($lines[$last]);
// write the new data to the file
$fp = fopen('filename.txt', 'w');
fwrite($fp, implode('', $lines));
fclose($fp);
?>