Home >Backend Development >PHP Problem >How to delete the last line of a file in php

How to delete the last line of a file in php

王林
王林Original
2020-08-04 14:21:273548browse

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 the file line by line and put the read content into an array; finally use array_pops() The function deletes the last element in the array.

How to delete the last line of a file in php

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.

(Recommended tutorial: php graphic tutorial)

Syntax:

array_pop(array)

fgets() function returns a line from the 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.

Grammar:

fgets(file,length)

(Video tutorial recommendation: php video tutorial)

Code implementation (for reference only):

/**
* 删除文件最后一行
* @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);
}

Analysis:

After my file is read, 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn