php文件开头加数据,在PHP中附加到文件的开头

标签: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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值