【发布时间】:2013-06-03 09:56:06
【问题描述】:
您好,我想使用 php 在文件开头追加一行。
例如,该文件包含以下内容:
Hello Stack Overflow, you are really helping me a lot.
现在我想像这样在前一行的顶部添加一行:
www.stackoverflow.com
Hello Stack Overflow, you are really helping me a lot.
这是我目前在脚本中的代码。
$fp = fopen($file, 'a+') or die("can't open file");
$theOldData = fread($fp, filesize($file));
fclose($fp);
$fp = fopen($file, 'w+') or die("can't open file");
$toBeWriteToFile = $insertNewRow.$theOldData;
fwrite($fp, $toBeWriteToFile);
fclose($fp);
我想要一些最佳解决方案,因为我在 php 脚本中使用它。以下是我在这里找到的一些解决方案: Need to write at beginning of file with PHP
在开头附加以下内容:
<?php
$file_data = "Stuff you want to add\n";
$file_data .= file_get_contents('database.txt');
file_put_contents('database.txt', $file_data);
?>
还有一个在这里: Using php, how to insert text without overwriting to the beginning of a text file
这样说:
$old_content = file_get_contents($file);
fwrite($file, $new_content."\n".$old_content);
所以我的最后一个问题是,在上述所有方法中,哪种方法是最好的(我的意思是最优的)。还有比上面更好的吗?
寻找您对此的想法!!!。
【问题讨论】:
-
来自手册
If filename does not exist, the file is created. Otherwise, the existing file is overwritten, unless the FILE_APPEND flag is set. -
@Robert,我的问题是,这是最好的方法。请完整阅读。我还提到了您在问题中可能重复的问题。
-
文件是否也在 PHP 中读取? (生成的文件是否在稍后被处理以供 PHP 读取?)
-
file_get_contents可能需要读取内存中的完整文件..如何像'w+'一样逐部分读取它? -
@ring0,我不太明白你的问题。我只用 php 读写。
标签: php