Skip to content
Tutorials Center
My learning

Topics

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
<?php
echo "Line one" . PHP_EOL . "Line two" . PHP_EOL;

Try it

PHP PHP_EOL and the escape sequences

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.

PHP Splitting text into lines

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

  • \n versus PHP_EOL. In CLI scripts, echo "text\n" works on Windows too. Use PHP_EOL only 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 an n.
  • file() keeps line endings unless you pass FILE_IGNORE_NEW_LINES, which strips "\n" and also a trailing "\r" so Windows files read cleanly.
  • fgets() returns the ending with the line; use rtrim() to remove it. The old auto_detect_line_endings ini setting (for files that use a lone carriage return) was deprecated in PHP 8.1.
  • nl2br() does not escape. Run htmlspecialchars() first, then nl2br(), so user text cannot inject markup.
  • explode("\n") on a Windows file leaves a trailing \r on each item. Prefer preg_split('/\R/', $s).
  • Heredocs (<<<EOT) contain the file's own line endings, so a script saved with Windows endings produces \r\n in the string.