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?
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?
From
main/php.h
of PHP version 7.1.1 and version 5.6.30:As you can see
PHP_EOL
can be"\r\n"
(on Windows servers) or"\n"
(on anything else). On PHP versions prior 5.4.0RC8, there were a third value possible forPHP_EOL
:"\r"
(on MacOSX servers). It was wrong and has been fixed on 2012-03-01 with bug 61193.As others already told you, you can use
PHP_EOL
in any kind of output (where any of these values are valid - like: HTML, XML, logs...) where you want unified newlines. Keep in mind that it's the server that it's determining the value, not the client. Your Windows visitors will get the value from your Unix server which is inconvenient for them sometimes.I just wanted to show the possibles values of
PHP_EOL
backed by the PHP sources since it hasn't been shown here yet...Handy with error_log() if you're outputting multiple lines.
I've found a lot of debug statements look weird on my windows install since the developers have assumed unix endings when breaking up strings.
DOS/Windows standard "newline" is CRLF (= \r\n) and not LFCR (\n\r). If we put the latter, it's likely to produce some unexpected (well, in fact, kind of expected! :D) behaviors.
Nowadays almost all (well written) programs accept the UNIX standard LF (\n) for newline code, even mail sender daemons (RFC sets CRLF as newline for headers and message body).
I have a site where a logging-script writes a new line of text to a textfile after an action from the user, who can be using any OS.
Using PHP_EOL don't seem to be optimal in this case. If the user is on Mac OS and writes to the textfile it will put \n. When opening the textfile on a windows computer it doesn't show a line break. For this reason i use "\r\n" instead which works when opening the file on any OS.
There is one obvious place where it might be useful: when you are writing code that predominantly uses single quote strings. Its arguable as to whether:
The art of it is to be consistent. The problem with mix and matching '' and "" is that when you get long strings, you don't really want to have to go hunting for what type of quote you used.
As with all things in life, it depends on the context.