我打算打开一个文件,抓住文件中line =“?>”的最后一行,这是php文档的结束标记。比我想要将数据附加到其中并添加回“?>”到最后一行。
我一直在尝试一些方法,但我没有运气。
这是我到目前为止所得到的,因为我正在阅读一个zip文件。虽然我知道这一切都错了,但只需要一些帮助......
// 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,但在我们删除等于'?&gt;'的最后一行后
好吧,我实际上做了一些改动,它似乎工作,但它现在复制数据两次... arggg,所以文件中的每一行现在在那里2次:(
好的,删除了fwrite,但现在它将它附加在底部,正好在?&gt;下面
OMG,我只需要一切到最后一行,是不是有办法做到这一点???我不需要“?&gt;”答案 0 :(得分:2)
文件系统上文件的简单方法:
<?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";
?>
答案 1 :(得分:0)
它会复制每一行两次,因为你的行说:
@fwrite($fp, $output);
您只是在阅读文件以找到结束标记,您无需在阅读时写下您读过的行。
答案 2 :(得分:0)
我会在最后一行之后添加一个新的<? YOUR CODE ?>
...
或者,如果要在$code
中添加新的PHP代码,可以使用regular expression
$output = preg_replace('\?>','?>'.$code,$output)