PHP Reference ยท String Functions
PHP_EOL and line endings
How PHP handles newlines: PHP_EOL, \n versus \r\n, splitting text into lines with preg_split and file(), and nl2br for HTML. Pitfalls across platforms.
A line ending is a character, or pair of characters, that marks the end of a line of text. Unix, Linux and macOS use a line feed ("\n", byte 0x0A). Windows traditionally uses a carriage return followed by a line feed ("\r\n"). Old classic Mac systems used a lone carriage return ("\r"), and you can still meet it in old files.
PHP_EOL is a constant holding the line ending of the platform PHP runs on: "\n" on Linux and macOS, "\r\n" on Windows. It is handy for text that is meant for the local system, but the format you send to other systems (HTTP, email, CSV, JSON, files shared between machines) should state its line ending explicitly instead.
<?php echo "Line one" . PHP_EOL . "Line two" . PHP_EOL;
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Which one to use
| Task | Use |
|---|---|
| Print a line to the console or a local log | PHP_EOL or "\n" |
| Output for the web | "\n", or nl2br() to show breaks in HTML |
| HTTP headers, SMTP, many network protocols | "\r\n" written out explicitly |
| CSV files read by Excel | "\r\n" (fputcsv() accepts an $eol argument since PHP 8.1) |
| Reading text of unknown origin | Split with preg_split('/\R/', ...) or open with file() |
Usage notes
\nversusPHP_EOL. In CLI scripts,echo "text\n"works on Windows too. UsePHP_EOLonly when you want the local convention; it makes output differ between servers, which complicates tests and diffs.- Escapes need double quotes. In a single-quoted string
'\n'is a backslash and ann. file()keeps line endings unless you passFILE_IGNORE_NEW_LINES, which strips"\n"and also a trailing"\r"so Windows files read cleanly.fgets()returns the ending with the line; usertrim()to remove it. The oldauto_detect_line_endingsini setting (for files that use a lone carriage return) was deprecated in PHP 8.1.nl2br()does not escape. Runhtmlspecialchars()first, thennl2br(), so user text cannot inject markup.explode("\n")on a Windows file leaves a trailing\ron each item. Preferpreg_split('/\R/', $s).- Heredocs (
<<<EOT) contain the file's own line endings, so a script saved with Windows endings produces\r\nin the string.
Related
nl2br(),explode(),rtrim(),file(), Predefined constants,fgets()- Lessons: Echo and print, File handling