如何在 php 中将数据添加到空白文件


How to add data to a blank file in php?

我一直在尝试让这段代码工作,但它不会。我正在尝试创建一个程序,该程序将信息添加到文件中,它创建了一个文件并添加数据。
对不起菜鸟的错误。

if (!empty($_POST['submit'])){
    $name=$_POST['name'];
    $comment=$_POST['stuff'];
    file_put_contents("names.txt",$names. PHP_EOL, FILE_APPEND);
    $names=file("names.txt");
    $i=count($names);
    file_put_contents("$i.txt",$comment);}
    $names=file("names.txt");
    foreach ($names as $name){
        file_get_contents("$i.txt");
        print "$name[$i]:$Name: #Comment";
    }
}

在这里你可以尝试什么

if (isset($_POST['submit'])) {
    $name = $_POST['name'];
    $comment = $_POST["stuff"];
    $myFile = fopen("names.txt", "a"); //Here "a" means every time you submit, it appends data to existing "names.txt".
    fwrite($myFile, "Name: ".$name."'n'r");
    fwrite($myFile, "Comment: ".$comment."'n'r");
    fclose($myFile);
    echo "$name: $comment"; //here I used "echo" instead of "print"
}

现在,当您提交另一个表单时,它会将内容放入现有的"名称.txt"中,而不会删除其文本。

您可以使用

fopen() 函数创建文件,如下所示:

if (!empty($_POST['submit'])){
  $name=$_POST['name'];
  $comment=$_POST['stuff'];
  $myFile = fopen("names.txt", "w");
  fwrite($myFile, "Name: ".$name."'n");
  fwrite($myFile, "Comment: ".$comment."'n");
  fclose($myFile);
  echo "Name: ".$name."<br>Comment: ".$comment."<br>";
}

前面的代码创建一个新的文本文件。如果要向现有文件添加信息,只需更改以下行:

  $myFile = fopen("names.txt", "w");

进入这一行:

  $myFile = fopen("names.txt", "a");

让我知道这是否适合您! :)