How to open textfile and write to it append-style with php?

不想你离开。 提交于 2020-06-07 04:58:25

问题


How do you open a textfile and write to it with php appendstyle

    textFile.txt

        //caught these variables
        $var1 = $_POST['string1'];
        $var2 = $_POST['string2'];
        $var3 = $_POST['string3'];

    $handle = fopen("textFile.txt", "w");
    fwrite = ("%s %s %s\n", $var1, $var2, $var3, handle);//not the way to append to textfile
fclose($handle);

回答1:


To append data to a file you would need to open the file in the append mode (see fopen):

  • '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.
  • 'a+'
    Open for reading and writing; place the file pointer at the end of the file. If the file does not exist, attempt to create it.

So to open the textFile.txt in write only append mode:

fopen("textFile.txt", "a")

But you can also use the simpler function file_put_contents that combines fopen, fwrite and fclose in one function:

$data = sprintf("%s %s %s\n", $var1, $var2, $var3);
file_put_contents('textFile.txt', $data, FILE_APPEND);


来源:https://stackoverflow.com/questions/2448887/how-to-open-textfile-and-write-to-it-append-style-with-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!