如何打开文本文件并使用 php 以追加样式写入它?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2448887/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 06:32:11  来源:igfitidea点击:

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

phptext-files

提问by Chris_45

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

你如何打开一个文本文件并用 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);

回答by Gumbo

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

要将数据附加到文件,您需要以附加模式打开文件(请参阅 参考资料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.
  • 'a'
    只开放写;将文件指针放在文件末尾。如果该文件不存在,请尝试创建它。
  • 'a+'
    开放读写;将文件指针放在文件末尾。如果该文件不存在,请尝试创建它。

So to open the textFile.txtin write only appendmode:

因此,要打开TextFile.txt的只写追加方式:

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

But you can also use the simpler function file_put_contentsthat combines fopen, fwriteand fclosein one function:

但是您也可以使用file_put_contentsfopen,fwrite和组合fclose在一个函数中的更简单的函数:

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