【问题标题】:Append file content to the top instead of bottom? [duplicate]将文件内容附加到顶部而不是底部? [复制]
【发布时间】:2016-06-26 23:30:36
【问题描述】:

我有一个表格,工作人员可以填写该表格将他们的消息发送到我们的更新页面。我的代码是

$filename = "files/armaupdates";
$text = $_POST['update'];

$updatesep = "<hr><br><hr><br>";

$fp = fopen($filename, "a+");

if($fp){
	fwrite($fp, $text);
	fwrite($fp, $updatesep);
	fclose($fp);
	echo "Updates has been written!";
}
else {
	echo "Error!";
}

我要疯了,因为我希望文本位于文件的顶部而不是底部,有人吗?

【问题讨论】:

  • 如何使用file_get_contents,根据新行展开内容,反转数组,追加到数组,反转回来,然后加入新行?
  • 有几种方法可以做到这一点,但它们都涉及重写整个文件,并在顶部添加前置内容。没有标志可以添加到文件中(就像有 a+ 可以添加到文件中一样)。

标签: php html


【解决方案1】:
$filename = "files/armaupdates";
$text = $_POST['update'];

$updatesep = "<hr><br><hr><br>";
$content = file_get_contents($filename);

$fp = fopen($filename, "w");

if($fp){
    fwrite($fp, ($text . $updatesep . $content));
    fclose($fp);
    echo "Updates has been written!";
}
else {
    echo "Error!";
}

【讨论】:

  • 太棒了,这成功了,谢谢你!
【解决方案2】:

只需在内容前添加新数据:

$updatedContents = $text . $updatesep . file_get_contents($filename);

给你代码:

$filename = "files/armaupdates";
$text = $_POST['update'];

$updatesep = "<hr><br><hr><br>";

$updatedContents = $text . $updatesep . file_get_contents($filename);

$fp = fopen($filename, "a+");

if($fp){
    fwrite($fp, $updatedContents);
    fclose($fp);
    echo "Updates has been written!";
}
else {
    echo "Error!";
}

【讨论】:

    猜你喜欢
    • 2019-02-10
    • 1970-01-01
    • 2021-10-01
    • 1970-01-01
    • 2012-10-22
    • 2017-01-16
    • 2015-03-09
    • 1970-01-01
    • 2018-09-09
    相关资源
    最近更新 更多