【问题标题】:How to add new data to the top of .txt without deleting in PHP [duplicate]如何在不删除 PHP 的情况下将新数据添加到 .txt 的顶部 [重复]
【发布时间】:2017-09-23 20:43:45
【问题描述】:

当我使用此代码时

$fp = fopen('data.txt', 'w');
fwrite($fp, $data);
fclose($fp);

它会覆盖文本。我也想要页脚的旧数据。那么,如何在不删除 PHP 的情况下将新数据添加到 .txt 的顶部

可能的 output.txt 和视图

(new) line8
(new) line7
(new) line6
(old) line5
(old) line4
(old) line3
(old) line2
(old) line1

【问题讨论】:

  • 您可以随时读取数据并连接到 $data 不是吗? :|
  • 文件变大时会很痛苦
  • @marmeladze 任何解决方案,如果尺寸更大
  • <?php $cmd1 = "echo 'Lorem ipsum' > some.txt"; $cmd2 = "cat some.txt big.txt > new.txt";shell_exec($cmd1);shell_exec($cmd2); ?> -)))

标签: php fopen fwrite fclose


【解决方案1】:
$txt = "col1 col2 col3 coln";
file_put_contents('data.txt', $txt.PHP_EOL , FILE_APPEND | LOCK_EX);

请试试这个。谢谢

【讨论】:

    【解决方案2】:

    您可以尝试将要添加的数据与“data.txt”文件中的数据连接起来。

    $data = "(new) line\n";
    file_put_contents("data.txt", $data . file_get_contents("data.txt"));
    

    【讨论】:

      【解决方案3】:

      您可以使用 PHP DOC file get contentsfile put contents

      <?php
      
      error_reporting(E_ALL); ini_set('display_errors', 1);
      
      $newdata = "4- whatever you need \n";
      $datafromfile = file_get_contents("data.inc.txt");
      file_put_contents("data.inc.txt", $newdata.$datafromfile);
      
      ?>
      

      【讨论】:

        【解决方案4】:

        尝试使用“a”模式而不是“w”模式打开文件。

        $fp = fopen('data.txt', 'a');
        

        来自 php 手册:fopen

        'w' 只为写入而打开;将文件指针放在文件的开头并将文件截断为零长度。如果文件不存在,请尝试创建它。

        'a' 只为书写而打开;将文件指针放在文件末尾。如果该文件不存在,请尝试创建它。在这种模式下,fseek() 没有任何作用,写入总是追加。

        【讨论】:

          猜你喜欢
          • 2021-02-04
          • 1970-01-01
          • 2023-03-24
          • 2014-07-13
          • 2017-01-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-03-29
          相关资源
          最近更新 更多