When write a string output to a file with file_put_contents function with FILE_APPEND flag in PHP, the text will be appended to the end of the line, without any line break.

There are several ways to force file_put_contents function to insert a new line or end of line (EOL) character to indicate the line ending, and allow the start of new line for the new data.

Here’s a few way to force the end of the line and start a new line when output to a file on PHP scripts.

Method 1: PHP_EOL PHP End of Line

Example:

$file = 'techjourney.txt';
$text = PHP_EOL . "Tech Journey";
file_put_contents($file, $text, FILE_APPEND);
When defining PHP_EOL at the beginning of the line, the new line may not be made because the end of line is added only after the line which supposed to be on the new content is written to the file.

Method 1: \r\n

Example:

$file = 'techjourney.txt';
$text = "Tech Journey\r\n";
file_put_contents($file, $text, FILE_APPEND);
“\r\n” is required if you’re viewing the file on Windows as Windows uses CR+LF for new line. On Lnux, only LF (“\n”) is required.