Home > Article > Backend Development > How to delete the last line of a file in php
php method to delete the last line of a file: first use the fopen() function to open a file; then use the fgets() function to read a line of content from the open file and save it to an array; finally Just use the array_pop() function to delete the last element in the array.
Related functions:
(Recommended tutorial: php graphic tutorial)
fopen( ) function opens a file or URL.
If fopen() fails, it will return FALSE with an error message. You can hide error output by adding an '@' in front of the function name.
fgets() function returns a line from an open file.
fgets() function will stop returning a new line when it reaches the specified length (length - 1), encounters a newline character, or reaches the end of file (EOF) (whichever comes first). The function returns FALSE on failure.
array_pop() function deletes the last element in the array. Returns the last value of the array. If the array is empty, or is not an array, NULL will be returned.
(Learning video recommendation: php video tutorial)
Code implementation:
/** * 删除文件最后一行 * @param $file_path 文件路径 */ public function delLastLine($file_path) { $file = $fp = fopen($file_path, 'r') or die("Unable to open file!"); while(!feof($file)) { $fp = fgets($file); if($fp) { $content[] = $fp; } } array_pop($content); fclose($file); //重新写入文件 $file = fopen($file_path, 'w+'); fwrite($file, implode("", $content)); fclose($file); }
Description:
My file reading After coming out, the last line of the array saves false, so if($fp) is written to the array. If there are blank lines in the file, please remove this judgment and delete the last line of the array twice. This method does not work if the file is too large to fit into memory.
The above is the detailed content of How to delete the last line of a file in php. For more information, please follow other related articles on the PHP Chinese website!