簡體   English   中英

用PHP在txt文件上寫一個新行?

[英]Write a new line on a txt file with PHP?

我想用PHP創建txt文件,可以在Form上輸入后保存數據。

到目前為止,我一直在嘗試這個腳本

<?php

if(isset($_POST[S1]))
{
   $name = $_POST[name];
   $email = $_POST[email];

   $fp = fopen("formdata.txt", "w") or exit("Unable to open file!");
   $savestring = $name . "," . $email . "\n";

   fwrite($fp, $savestring);

   fclose($fp);
   echo "<h1>You data has been saved in a text file!</h1>";

?>
<form name="web_form" id="web_form" method="post" action="coba.php">
        Enter name: </label><input type="text" name="name" id="name" />
        Enter email: </label><input type="text" name="email" id="email" />
        <input type="submit" name="S1" id="s1″ value="Submit" />
</form>

它工作正常,可以在輸入表單后寫入文件,但如果我執行第二次輸入,則txt文件將更改為最后一個輸入。

如何在第二次輸入時,最后一次輸入在txt文件上寫一個新行?

可能是這個例子不清楚的解釋

    ===============================
    First Input:
    Result Txt File:

    Adam, Adam@email.com
    ===============================
    Second Input:
    Result Txt File:

    Adam, Adam@email.com
    Eve, Eve@gmail.com
    =============================== 

有人可以幫我解決嗎? 我非常感謝您的回答。

謝謝

追加模式打開文件:

$fp = fopen("formdata.txt", "a") or exit("Unable to open file!");

或者將file_put_contentsFILE_APPEND標志一起使用:

file_put_contents("formdata.txt", $name . "," . $email . "\n", FILE_APPEND);

注意:

如果您在Windows環境下運行它,則需要使用\\r\\n

即:

file_put_contents("formdata.txt", $name . "," . $email . "\r\n", FILE_APPEND);

\\n單獨是下了UNIX / Linux平台,但不適用於Windows充足。

您還可以使用跨平台的PHP_EOL預定義常量

file_put_contents("formdata.txt", $name . "," . $email . PHP_EOL, FILE_APPEND);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM