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.
PHP_EOL is useful when you're writing data to a file, example a log file. It will create line breaks specific to your platform.
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.The
PHP_EOL
define is correct for the platform that you are on. So on windowsPHP_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.)When you are using PHP to make a web app, there are a few layers involved:
Note that in the above, it is just data that is being passed along. In your case, that data is HTML, but it could just as easily be plain text or even a PNG formatted image. (This is one reason why you send a
Content-Type:
header, to specify the format of your data.)Because it is so often used for HTML, PHP has a lot of HTML-specific features, but that's not the only format it can output. So, while a newline character is not always useful for HTML, is is useful: