Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

New line in PHP output in a text file

My php form which saves the output in a text file glues the result to one string like:

Name1Email1The Message1Name2Email2The Message2Name3Email3The Message3Name4Email4The Message4

But I need spaces and/or newlines. I normaly don't use PHP so I don't get it. I did't find an answer on the web, also read some Q/A here, but this didn't help me.

The Form:

<form action="mailer.php?savedata=1" method="post">
Your Name: <input type="text" name="name"><br>
Your Email: <input type="text" name="email"><br>
Your Message:<br> <textarea name="message" rows="5" cols="30"></textarea><br>
<input type="submit" name="submit" value="Submit">
</form>

The PHP

<?php
$savedata = $_REQUEST['savedata'];
if ($savedata == 1){ 
$data = $_POST['name'];
$data .= $_POST['email'];
$data .= $_POST['message'];
$file = "YOURDATAFILE.txt"; 

$fp = fopen($file, "a") or die("Couldn't open $file for writing!");
fwrite($fp, $data) or die("Couldn't write values to file!"); 

fclose($fp); 
echo "Your Form has been Submitted!";

}
?>
like image 953
Darth Severus Avatar asked Oct 16 '12 05:10

Darth Severus


People also ask

How do you make a new line in a text file?

You put the slash for the newline character backwards. It should be: "\n".

Can we use \n in PHP?

It is an in-built function of PHP, which is used to insert the HTML line breaks before all newlines in the string. Although, we can also use PHP newline character \n or \r\n inside the source code to create the newline, but these line breaks will not be visible on the browser.

What is \n in a file?

But the result in the text file is a newline. I know that the \n represents a newline.

What is Br in PHP?

Example. Insert line breaks where newlines (\n) occur in the string: echo nl2br("One line. \nAnother line.");


2 Answers

You can use "\n" to write a new line.

$data = $_POST['name'] . "\n";
$data .= $_POST['email'] . "\n";
$data .= $_POST['message'] . "\n";

Just as a sidenote, \n has to be in doublequotes. When surrounded by single quotes it won't work.

like image 79
Louis Huppenbauer Avatar answered Sep 20 '22 05:09

Louis Huppenbauer


As other answers state, you need to add in an end of line character after each field.

Different OS's use different line endings, though, and so a "\n" may not display as a new line on Windows, for example. As Mahdi said, you can use Windows style "\r\n" line endings, or you can use the PHP_EOL constant so that line endings appropriate to the server will be output, in which case your code would look like

$data = $_POST['name'] . PHP_EOL;
$data .= $_POST['email'] . PHP_EOL;
$data .= $_POST['message'] . PHP_EOL;
like image 43
Dallin Avatar answered Sep 20 '22 05:09

Dallin