Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

When do I use the PHP constant “PHP_EOL”?

When is it a good idea to use PHP_EOL?

I sometimes see this in code samples of PHP. Does this handle DOS/Mac/Unix endline issues?
by

4 Answers

rahul07
Yes, PHP_EOL is ostensibly used to find the newline character in a cross-platform-compatible way, so it handles DOS/Unix issues.

Note that PHP_EOL represents the endline character for the current system. For instance, it will not find a Windows endline when executed on a unix-like system.
sandhya6gczb
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. So you might follow your <br /> with a PHP_EOL.

You would use it if you are running php as a script from cron and you needed to output something and have it be formatted for a screen.

You might use it if you are building up an email to send that needed some formatting.
RoliMishra
The definition of PHP_EOL is that it gives you the newline character of the operating system you're working on.

In practice, you should almost never need this. Consider a few cases:

When you are outputting to the web, there really isn't any convention except that you should be consistent. Since most servers are Unixy, you'll want to use a "\n" anyway.

If you're outputting to a file, PHP_EOL might seem like a good idea. However, you can get a similar effect by having a literal newline inside your file, and this will help you out if you're trying to run some CRLF formatted files on Unix without clobbering existing newlines (as a guy with a dual-boot system, I can say that I prefer the latter behavior)

PHP_EOL is so ridiculously long that it's really not worth using it.
pankajshivnani123
PHP_EOL (string) The correct 'End Of Line' symbol for this platform. Available since PHP 4.3.10 and PHP 5.0.2

You can use this constant when you read or write text files on the server's filesystem.

Line endings do not matter in most cases as most software are capable of handling text files regardless of their origin. You ought to be consistent with your code.

If line endings matter, explicitly specify the line endings instead of using the constant. For example:

HTTP headers must be separated by \r\n
CSV files should use \r\n as row separator

Login / Signup to Answer the Question.