What is the advantage of \ n and PHP_EOL in PHP?

I am trying to output a newline character in PHP that is being viewed in a web browser. I can only manage this with the <br /> tag.

When I use \n , nothing happens, so what's the use of using \n ? And what is the advantage of PHP_EOL ? When I concatenate it with a line, just the space is not printed on a new line.

+7
source share
4 answers

The web browser interprets the output of the PHP program as HTML, so \n and \r\n will not do anything like insert a new line into an HTML file. On the other hand, <br /> creates a new line in the interpreted HTML (hence the "line BReak"). Therefore, <br /> will create new lines, while \r\n do nothing.

+7
source

When you use PHP to create a web application, there are several layers:

  • Your PHP code that outputs some data in
  • a web server that transmits data over the network to
  • A web browser that analyzes data and displays it on the screen.

Note that in the above example, this is just data that is transmitted together. In your case, this data is HTML, but it can be just plain text or even a PNG image. (This is one of the reasons you send the Content-Type: header to indicate the format of your data.)

Because it is so often used for HTML, PHP has many HTML-specific functions, but this is not the only format it can output. Thus, although the newline character is not always useful for HTML, it is useful:

  • if you want to format the generated HTML code, not for a web browser, but for another person who can read,
  • if you want to create plain text or another format in which newlines are important.
+4
source

The PHP_EOL definition PHP_EOL correct for the platform you are on. Thus, on windows PHP_EOL there is \r\n on MAC it \r on Linux, it \n . Whereas <br /> or <br> is HTML markup for the linear brake. If you are new to HTML and PHP, it is best to get an idea of ​​HTML first and then worry about PHP. Or start reading some source code and run the source code of other people to find out how they did it. This will make your code better by simply copying their style. (In most cases.)

+3
source

PHP_EOL is useful when you write data to a file, such as a log file. This will create line breaks specific to your platform.

+2
source

All Articles