Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I remove the last line of a file using php?

Tags:

php

I've tried a lot of potential solutions, but none of them are working for me. The simplest one:

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

isn't doing anything at all. Am I doing something wrong here? Is it different because it's an html file?

like image 603
jemtan990 Avatar asked Jun 29 '13 15:06

jemtan990


People also ask

How do you delete a line in PHP?

The line break can be removed from string by using str_replace() function.

How do I delete a file in PHP?

The unlink() function deletes a file.


1 Answers

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); 

?>
like image 156
Xavier Avatar answered Oct 11 '22 14:10

Xavier