标签:php
让我们说例如该文件包含以下contnet:
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
在开头追加以下内容:
$file_data = "Stuff you want to add\n";
$file_data .= file_get_contents('database.txt');
file_put_contents('database.txt', $file_data);
?>
说如下:
$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');
标签:php
来源: https://codeday.me/bug/20190725/1534219.html