简单的PHP函数从文本文件中删除最后一行不起作用 [英] Simple PHP function to remove the last line from text file not working
本文介绍了简单的PHP函数从文本文件中删除最后一行不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个名为test
的文本文件,只有两行:
I have a text file named test
with only 2 lines:
1
2
我希望能够从文件中删除最后一行,因此我使用以下功能:
I want to be able to remove the last line from the file so I use the following function:
<?php
$file = file('test.txt');
array_pop($file);
file_put_contents(implode($file));
?>
由于某种原因,它什么也不做,文件仍然有确切的行..我在这里遗漏了什么吗?
For some reason, this does nothing and the file still has the exact lines..am I missing something here?
推荐答案
文件 函数仅将文件的内容(作为数组)返回给您-对该数组执行的任何操作仅更改数组,而不更改文件.要保留更改,请将内容写回到文件中:
file function only returns you the contents of a file (as an array) - and whatever you do with that array, only changes the array, not the file. To persist the changes, write the contents back to the file:
$filename = 'test.txt';
$arr = file($filename);
if ($arr === false) {
die('Failed to read ' . $filename);
}
array_pop($arr);
file_put_contents($filename, implode(PHP_EOL, $arr));
这篇关于简单的PHP函数从文本文件中删除最后一行不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文