如何打开文件并删除最后一行? [英] How to open a file and remove the last line?
问题描述
我想打开一个文件,抓住文件的最后一行,其中line =?>",这是php文档的结束标记.比我想在其中添加数据并在最后一行添加?>".
I am looking to open up a file, grab the last line in the file where the line = "?>", which is the closing tag for a php document. Than I am wanting to append data into it and add back in the "?>" to the very last line.
我一直在尝试一些方法,但是我没有运气.
I've been trying a few approaches, but I'm not having any luck.
这是我到目前为止从zip文件中读取的内容.尽管我知道这全都错了,但是请对此有所帮助...
Here's what I got so far, as I am reading from a zip file. Though I know this is all wrong, just needing some help with this please...
// Open for reading is all we can do with zips and is all we need.
if (zip_entry_open($zipOpen, $zipFile, "r"))
{
$fstream = zip_entry_read($zipFile, zip_entry_filesize($zipFile));
// Strip out any php tags from here. A Bit weak, but we can improve this later.
$fstream = str_replace(array('?>', '<?php', '<?'), '', $fstream) . '?>';
$fp = fopen($curr_lang_file, 'r+');
while (!feof($fp))
{
$output = fgets($fp, 16384);
if (trim($output) == '?>')
break;
}
fclose($fp);
file_put_contents($curr_lang_file, $fstream, FILE_APPEND);
}
$curr_lang_file
是实际文件的文件路径字符串,需要在其上附加fstream,但是在删除了最后一行等于'?>'
$curr_lang_file
is a filepath string to the actual file that needs to have the fstream appended to it, but after we remove the last line that equals '?>'
好吧,我实际上进行了一些更改,并且似乎可以正常工作,但是现在它在其中复制了两次数据... arggg,所以文件中的每一行现在都在其中2次了:(
Ok, I actually made a few changes, and it seems to work, BUT it now copies the data in there twice... arggg, so each line in the file is now in there 2 times :(
好吧,删除了fwrite,尽管现在它是将它附加在底部,即?>的正下方.
Ok, removed the fwrite, though now it is appending it at the bottom, just below the ?>
OMG,我只需要最后一行的所有内容,没有办法做到这一点吗???我不需要?>"
OMG, I just need everything up to the last line, isn't there a way to do this??? I don't need "?>"
推荐答案
在文件系统上处理文件的简单方法:
A simple way with the file on the filesystem:
<?php
$path = "file.txt";
$content = file($path); // Parse file into an array by newline
$data = array_pop($content);
if (trim($data) == '?>') {
$content[] = 'echo "... again";';
$content[] = "\n$data";
file_put_contents($path, implode($content));
}
是哪个.
$ cat file.txt
<?php
echo 'Hello world';
?>
$ php test.php
$ cat file.txt
<?php
echo 'Hello world';
echo "... again";
?>
这篇关于如何打开文件并删除最后一行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!