How to Create New Lines in PHP
To create a new line, rather than outputting the character used on the system, it is recommended that developers use the PHP_EOL constant in order to improve portability of their code.
Edited: 2019-12-31 06:14
PHP_EOL is a predefined constant that helps to improve the compatibility of PHP applications with various platforms. It works by automatically choosing the End Of Line symbol in use on the system that PHP is running on.
In Windows, a new line is denoted using \r\n, also known as Carriage Return (CRLF), while Linux and Mac uses the Unix-style \n delimiter.
It is recommended that you avoid the use of "\n" to create new lines in order to improve compatibility with other operating systems.
PHP_EOL can be used the same way you would use \n:
echo 'Hallo World' . PHP_EOL;
Outputs:
Hallo World
[LF]
Note. Since line breaks are invisible, we used [LF] to show a line feed where the break was outputted.
New lines vs visual line breaks
A new line character is not the same as a visible line break in a browser. A visible line break is usually created by margin and padding in CSS, while a new line in plain text is simply a type of whitespace character, which will be collapsed and/or ignored entirely in HTML browsers.
If you want to make a HTML line break, then you should instead echo out the br element, or usually better, close the current paragraph (p) element and open a new one. I.e:
// Using the br element to create a line break
echo '<br>';
// or using a paragraph
echo '<p>hallo world</p>';
echo '<p>It is a beautiful day to code in PHP.</p>';
E-mails and new-lines
When you are trying to separate header fields in e-mails, remember that your MTA (Mail Transfer Agent) might automatically translate whatever new line delimiter you are using into the correct one.
See also: PHP: mail
This means that it might not matter if you use carriage return (CRLF) or line line (LF) feed to separate the header fields.
HTTP Headers and New Lines
PHP_EOL should be avoided when manually sending HTTP headers, since individual headers are separated by Carriage Return.
To create a Carriage Return in PHP, you can echo something like this:
$aHTTP['http']['header'] = "User-Agent: My PHP Script\r\n";
$aHTTP['http']['header'] .= "Referer: https://beamtic.com/\r\n";
See also: Sending HTTP Requests from PHP
Tell us what you think: