[英]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?
我有以下程序,其中有一個文本框和兩個按鈕,即保存和提取。 如果單擊“提取”,它將顯示“ 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。 我想在這里換行。 如何解決呢? 請有人幫忙。
在將字符串保存到文件之前,在字符串前添加換行符:
file_put_contents("names.txt", PHP_EOL . $current_names, FILE_APPEND);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.