我是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>
这是我的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";
}
?>
答案 0 :(得分: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";
}
我希望它适合你。 :)