我有下面的程序,它有一个文本框和两个按钮,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"文件中
- 约翰
- 彼得
- 大卫
在文本框中输入的新名称集
- Julia
- Naomi
- Rachel
当我点击"保存"按钮时,新名称以以下格式附加到旧名称
- 约翰
- 彼得
- 大卫4.朱莉娅
- Naomi
- Rachel
但我想把茱莉亚放在下一行。我想在这里插队。如何解决这个问题?请有人帮忙。
在将换行符保存到文件之前,先在字符串中添加换行符:
file_put_contents("names.txt", PHP_EOL . $current_names, FILE_APPEND);