I'm very new to PHP. I have a FORM to input data, the FORM includes 3 fields : name, age, address I want to get the submitted data and write them to a text file line-by-line. For example, if I submit the FORM 3 times, I would like the output text file to contain:
john
20
US
Simson
18
UK
Marry
26
Japan
I tried to implement it, but there was always a blank space in the beginning or 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:
<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>
Here is my PHP script:
<?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";
}
?>
PHP Write to File - fwrite() The fwrite() function is used to write to a file. The first parameter of fwrite() contains the name of the file to write to and the second parameter is the string to be written.
The file_put_contents() function in PHP is an inbuilt function which is used to write a string to a file. The file_put_contents() function checks for the file in which the user wants to write and if the file doesn't exist, it creates a new file.
Just change your code:
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";
}
I hope it works for you. :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With