简体   繁体   中英

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?

I have the following program, which has a text box and two buttons, Save and Fetch. If Fetch is clicked, it will display the list of names present in the 'names.txt' file. If Save is clicked, it will save the names (append mode) entered in the text box into the list of names in the 'names.txt' file.

<!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);
}

?>

The program works fine, but the only problem is when a new set of names is append to the old set of names in the 'names.txt' file, the first name of the new set of names joins to the last name of the old set of names. I've explained below in detail with an example-

Example:

Names already in 'names.txt' file

  1. John
  2. Peter
  3. David

New set of names entered in the text box

  1. Julia
  2. Naomi
  3. Rachel

When i click 'Save' button the new names append to the old names in the following format

  1. John
  2. Peter
  3. David4. Julia
  4. Naomi
  5. Rachel

But i want to store Julia in next line. I want a line break here. How to solve this? Please someone help in this.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM