How to delete the last line of a file using php?

I have tried many potential solutions, but none of them work for me. Simplest:

$file = file('list.html'); array_pop($file); 

doing nothing. Am I something wrong here? Is this different because it is an html file?

+7
source share
4 answers

This should work:

 <?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); ?> 
+9
source

Delete the first and last line of a variable in PHP:

Using the phph interactive shell:

 php> $test = "line one\nline two\nline three\nline four"; php> $test = substr($test, (strpos($test, "\n")+1)); php> $test = substr($test, 0, strrpos($test, "\n")); php> print $test; line two line three 

Perhaps you meant "Last non-empty line." In this case, do the following:

Note that there are three blank lines after the content. This removes these lines before removing the latter:

 php> $test = "line one\nline two\nline three\nline four\n\n\n"; php> $test = substr($test, 0, strrpos(trim($test), "\n")); php> print $test; line one line two line three 
0
source

I created a function to remove x the number of rows from the bottom. Set $max 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 as follows:

 trim_lines("filename.txt", 1); 

The $path variable can be a path to a file or a file name.

0
source

You are only reading the file, now you need to write the file

Take a look at file_put_contents etc.

-2
source

All Articles