How to Add Line Break (Start New Line) in PHP

»»»How to Add Line Break (Start New Line) in PHP

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


$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


$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.

By |2016-12-10T21:43:30+00:00December 10th, 2016|Categories: Developer Tools|Tags: , |0 Comments

About the Author:

LK is a technology writer for Tech Journey with background of system and network administrator. He has be documenting his experiences in digital and technology world for over 15 years. Connect with LK through Tech Journey on Facebook, Twitter or Google+.