如何用换行符将一组数据(名称)附加到PHP文本文件中现有的一组数据上


How to append a set of data(names) with a line break to the existing set of data(names) in a text file in PHP?

我有下面的程序,它有一个文本框和两个按钮,Save和Fetch。如果单击"获取",它将显示"names.txt"文件中的名称列表。如果单击"保存",它将把在文本框中输入的名称(附加模式)保存到"names.txt"文件中的名称列表中。

<!DOCTYPE html>
<html>
<head>
<title>Form Page</title>    
</head>
<body>
<form action="Files.php" method="POST">
<textarea rows="15" cols="30" value="textbox" name="textbox"></textarea></br>
<input type="submit" value="Save" name="Save">
<input type="submit" value="Fetch" name="Fetch">
</form>
</body>
</html>
<?php
/*** Get names from 'names.txt' file and prints the names stored in it ***/
if(isset($_POST['Fetch'])){
    $file_names = "names.txt";
    $current_names = file_get_contents($file_names);
    echo nl2br($current_names); 
}
/*** Get names from text box and Put to the 'names.txt' file in append mode ***/
if(isset($_POST['Save'])){
    $current_names = $_POST["textbox"];
    file_put_contents("names.txt", $current_names, FILE_APPEND);
    /*** Get names form 'names.txt' file and prints the names stored in it ***/
    $file_names = "names.txt";
    $current_names = file_get_contents($file_names);
    echo nl2br($current_names);
}
?>

该程序运行良好,但唯一的问题是,当将一组新名称附加到"names.txt"文件中的旧名称集时,新名称集的第一个名称与旧名称集的最后一个名称连接。我在下面用一个例子详细解释了

示例:

名称已在"Names.txt"文件中

  1. 约翰
  2. 彼得
  3. 大卫

在文本框中输入的新名称集

  1. Julia
  2. Naomi
  3. Rachel

当我点击"保存"按钮时,新名称以以下格式附加到旧名称

  1. 约翰
  2. 彼得
  3. 大卫4.朱莉娅
  4. Naomi
  5. Rachel

但我想把茱莉亚放在下一行。我想在这里插队。如何解决这个问题?请有人帮忙。

在将换行符保存到文件之前,先在字符串中添加换行符:

file_put_contents("names.txt", PHP_EOL . $current_names, FILE_APPEND);