Use \n for CLI scripts on Unix systems; 2. Apply nl2br() for browser line breaks in HTML; 3. Use \r\n for cross-platform file compatibility; 4. Utilize PHP_EOL constant for server-agnostic line endings.
When outputting text in PHP, using the correct line break character is essential for formatting. Here's how to properly use newline characters in different contexts:
The operating environment of this tutorial: MacBook Pro, macOS Sonoma
The \n character is the standard newline in Unix-based systems and works correctly when running PHP scripts via the command line interface (CLI). It tells the terminal to move to the next line.
Web browsers do not interpret \n as a visual line break because HTML uses
tags. The nl2br() function converts newline characters into HTML
tags automatically.
Windows systems expect both a carriage return (\r) and line feed (\n), written as \r\n. This combination ensures compatibility across different platforms, especially when generating files or logs.
web applicationsPHP provides the built-in constant PHP_EOL which returns the correct end-of-line marker based on the server’s operating system. This is ideal for log files or CLI output where portability matters.