What is the benefit of \n and PHP_EOL in PHP?
I'm trying to output a newline character in PHP that gets viewed in a web browser. I can only mana开发者_如何学Pythonge 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.
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 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.)
When you are using PHP to make a web app, there are a few layers involved:
- Your PHP code, which outputs some data to
- a web server, which transmits the data over the network to
- a web browser, which parses the data and displays it on the screen.
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:
- if you want to format the HTML you are generating, not for the web browser, but for another person to be able to read;
- if you want to generate plain text or another format where newline characters do matter.
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.
精彩评论