如何打开一个文本文件并用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);
要将数据附加到文件中,您需要以附加模式打开文件(请参阅
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.
所以在只写append模式下打开textFile.txt:
fopen("textFile.txt","a")
但您也可以使用将fopen,fwrite和fclose组合在一起的更简单的功能file_put_contents
:
$data = sprintf("%s %s %s\n",$var3); file_put_contents('textFile.txt',$data,FILE_APPEND);