PHP file is written with a new line

I am doing a chat with a text file. Very simple, but I do not want it to put a damper on the server. Anyway. When I try to make a message, it adds the added message to the same line as

Alan,5/6/12,message<br>Joe,5/6/12,hello<br>

I wish it were

Alan,5/6/12,message
Joe,5/6/12,hello

This is what I have.

$total = 'Alan,5/6/12,hello joe<br>\r\n';
$fn = "messages.txt";
$file = fopen($fn,"a");
fwrite($fn,$total);
fclose($fn);

Thank.

+3
source share
3 answers
$total = 'Alan,5/6/12,hello joe<br>\r\n';

would work if you used double quotes like

$total = "Alan,5/6/12,hello joe<br>\r\n";
         ^--                           ^--

single quotes do not interpret metacharacters such as linebreak / newline, and your entire version with one quote is placed in the output of the literal character rand n.

+5
source

Try using PHP_EOLat the end:

$total = 'Alan,5/6/12,hello joe<br>' . PHP_EOL;
+2
source

Since it looks like you're writing CSV, you can make it simpler:

<? //PHP 5.4+
(new \SplFileObject('messages.txt', 'a'))->fputcsv([
  'Alan',  //or $user
  \date('c'), //or other date format
  'message content', //or $message_content
]);
?>
0
source

All Articles