【问题标题】:Update/Modify existing file on server更新/修改服务器上的现有文件
【发布时间】:2017-12-08 15:12:40
【问题描述】:

我想在每次页面加载时向文件添加内容,但它会覆盖文件,而不是更新内容。我的原始代码:

$file_handle = fopen('log.txt', 'w'); 
fwrite($file_handle, $message);
fclose($file_handle);

我搜索后,没有找到解决我的问题:

How to edit/update a txt file with php

PHP Modify a single line in a text file

我使用了w+r+,但没有用。

$file_handle = fopen('log.txt', 'w+'); 
fwrite($file_handle, $message);
fclose($file_handle);

都用新内容写入文件,而不是保留旧内容。我想保留旧内容,只需将新内容附加到现有文件即可。

【问题讨论】:

    标签: php


    【解决方案1】:

    您正在尝试附加到文件,因此您需要 mode 'a':

    $file_handle = fopen('log.txt', 'a'); 
    fwrite($file_handle, $message);
    fclose($file_handle);
    

    来自docs

    'a': Open for writing only; place the file pointer at the end of the file. If the file does not exist, attempt to create it. In this mode, fseek() has no effect, writes are always appended.

    【讨论】:

      猜你喜欢
      • 2011-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-28
      • 1970-01-01
      • 2018-02-06
      • 1970-01-01
      • 2020-02-26
      相关资源
      最近更新 更多