嗨,我想使用 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 脚本中使用它。以下是我在这里找到的一些解决方案:需要用 PHP 在文件开头写入
其中说以下内容要附加到开头:
<?php
$file_data = "Stuff you want to add'n";
$file_data .= file_get_contents('database.txt');
file_put_contents('database.txt', $file_data);
?>
另一个在这里:使用 php,如何在不覆盖文本文件开头的情况下插入文本
说:
$old_content = file_get_contents($file);
fwrite($file, $new_content."'n".$old_content);
所以我的最后一个问题是,在上述所有方法中,哪种方法是最好的方法(我的意思是最佳方法(。还有比上面更好的吗?
寻找你对此的看法!!.
function file_prepend ($string, $filename) {
$fileContent = file_get_contents ($filename);
file_put_contents ($filename, $string . "'n" . $fileContent);
}
用法:
file_prepend("couldn't connect to the database", 'database.logs');
写入文件时,我个人的偏好是使用file_put_contents
从手册:
此函数与调用 fopen((、fwrite(( 和 fclose(( 相同。 依次将数据写入文件。
由于该函数会自动为我处理这三个函数,因此我不必记住在完成资源后关闭资源。
没有真正有效的方法可以在文件的第一行之前写入。您的问题中提到的两种解决方案都通过复制旧文件的所有内容来创建一个新文件,然后写入新数据(这两种方法之间没有太大区别(。
如果您真的追求效率,即避免现有文件的整个副本,并且您需要让最后插入的行成为文件中的第一行,这完全取决于您计划在创建文件后如何使用该文件。
三个文件
根据你的评论,你可以创建三个文件header
、content
和footer
并按顺序输出每个文件;即使header
是在content
之后创建的,也可以避免复制。
在一个文件中反向工作
此方法将文件放在内存(数组(中。
由于您知道您在页眉之前创建了内容,因此请始终以相反的顺序编写行,页脚,内容,然后是标题:
function write_reverse($lines, $file) { // $lines is an array
for($i=count($lines)-1 ; $i>=0 ; $i--) fwrite($file, $lines[$i]);
}
然后你首先用页脚调用write_reverse()
,然后是内容,最后是页眉。每次你想在文件的开头添加一些东西时,只需在最后写
然后读取文件进行输出
$lines = array();
while (($line = fgets($file)) !== false) $lines[] = $line;
// then print from last one
for ($i=count($lines)-1 ; $i>=0 ; $i--) echo $lines[$i];
然后还有另一个考虑因素:您能否完全避免使用文件 - 例如通过 PHP APC
你的意思是前置。我建议您阅读该行并将其替换为下一行,而不会丢失数据。
<?php
$dataToBeAdded = "www.stackoverflow.com";
$file = "database.txt";
$handle = fopen($file, "r+");
$final_length = filesize($file) + strlen($dataToBeAdded );
$existingData = fread($handle, strlen($dataToBeAdded ));
rewind($handle);
$i = 1;
while (ftell($handle) < $final_length)
{
fwrite($handle, $dataToBeAdded );
$dataToBeAdded = $existingData ;
$existingData = fread($handle, strlen($dataToBeAdded ));
fseek($handle, $i * strlen($dataToBeAdded ));
$i++;
}
?>