如何在PHP中逐行编写文本文件?

Việ*_* Lê 4 php file

我是PHP的新手.我有一个FORM输入数据,FORM包括3个字段:名称,年龄,地址我想获取提交的数据,并逐行写入文本文件.例如,如果我在FORM上提交3次,我将在下面提供以下文本文件:

john
20
US
Simson
18
UK
Marry
26
Japan

I tried to implement it, but there was always a blank space in the beginning of text file, or there was always a blank space in the end of text file.I could not write file line by line. How do I do that, please help me ?
here is my form :<br>

<form action="themSinhVien.php" method="POST"> 
    <table id="tableHome"> 
        <tr> 
            <td id="td1"> 
                <span> Name: </span>
            </td>
            <td id="td2"> 
                <input type="text" name="name" placeholder="put your name here">
            </td>
        </tr>

        <tr> 
            <td id="td1"> 
                <span> Age: </span>
            </td>
            <td id="td2"> 
                <input type="text" name="age" placeholder="put your age here">
            </td>
        </tr>

        <tr> 
            <td id="td1"> 
                <span> Adress: </span>
            </td>
            <td id="td2"> 
                <input type="text" name="address" placeholder="put your address here">
            </td>
        </tr>


        <tr> 
            <td id="td1" style="padding-left:180px"> 
                <input type="submit" name="submit" value="Submit">
            </td>
            <td id="td2"> 
                <input type="reset" name="reset" value="reset">
            </td>
        </tr>

    </table>
</form>
Run Code Online (Sandbox Code Playgroud)

这是我的PHP脚本:

<?php 
    if( isset($_POST['submit']) ){
        $name = "\r\n".$_POST['name'];
        $age = "\r\n".$_POST['age']."\r\n";
        $address = $_POST['address'];                   
        $file = fopen("student.txt","a",1);
        fwrite($file,$name);
        fwrite($file,$age);
        fwrite($file,$address);
        fclose($file);
        echo "Adding student successfully";
    }
?>
Run Code Online (Sandbox Code Playgroud)

小智 6

只需更改您的代码:

if( isset($_POST['submit']) ){
                    $name = $_POST['name'];
                    $age = $_POST['age'];
                    $address = $_POST['address'];                   
                    $file = fopen("student.txt","a");
                    fwrite($file,$name.PHP_EOL);
                    fwrite($file,$age.PHP_EOL);
                    fwrite($file,$address.PHP_EOL);
                    fclose($file);
                    echo "Adding student successfully";
                }
Run Code Online (Sandbox Code Playgroud)

我希望这个对你有用.:)