I'm trying to output a newline character in PHP that gets viewed in a web browser. I can only manage it by using the <br />
tag.
When I use \n
, nothing occurs, so what is the benefit of using \n
? Also what is the benefit of PHP_EOL
? When I concatenate it to a string, just a space is printed not a newline.
You use PHP_EOL when you want a new line, and you want to be cross-platform. This could be when you are writing files to the filesystem (logs, exports, other). You could use it if you want your generated HTML to be readable.
Using new line tags: Newline characters \n or \r\n can be used to create a new line inside the source code.
You can use the PHP newline characters \n or \r\n to create a new line inside the source code. However, if you want the line breaks to be visible in the browser too, you can use the PHP nl2br() function which inserts HTML line breaks before all newlines in a string.
<br /> is a HTML line-break, whereas \n is a newline character in the source code. In other words, <br /> will make a new line when you view the page as rendered HTML, whereas \n will make a new line when you view the source code.
The PHP_EOL
define is correct for the platform that you are on. So on windows PHP_EOL
is \r\n
on MAC it's \r
on Linux, it's \n
. Whereas <br />
or <br>
is the HTML markup for line brake. If you're new to HTML & PHP, it's better to get a grasp of HTML first, then worry about PHP. Or start reading some source code, and run other peoples source code to see how they have done it. It will make you're code better just by copying their style. (Most of the time.)
A web browser interprets the output of a PHP program as HTML, so \n
and \r\n
will not appear to do anything, just like inserting a newline in an HTML file. On the other hand, <br />
makes a new line in the interpreted HTML (hence "line BReak"). Therefore, <br />
will make new lines, whereas \r\n
will not do anything.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With