Use for CLI scripts on Unix systems; 2. Apply nl2br() for browser line breaks in HTML; 3. Use 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
1. Using for newlines in Command Line scripts
The 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.
Write your PHP script with echo "Line 1Line 2";Run the script using php filename.php in the terminalYou will see each string after printed on a new line2. Outputting Line Breaks in Web Browsers with nl2br()
Web browsers do not interpret as a visual line break because HTML uses
tags. The nl2br() function converts newline characters into HTML
tags automatically.
Topaz Video AI 一款工业级别的视频增强软件
388 查看详情
立即学习“PHP免费学习笔记(深入)”;
Use echo nl2br("Line 1Line 2");This outputs Line 1 followed by atag and then Line 2The browser renders it as two separate lines
3. Combining for Cross-Platform Compatibility
Windows systems expect both a carriage return () and line feed (), written as . This combination ensures compatibility across different platforms, especially when generating files or logs.
Use file_put_contents('log.txt', "Entry 1Entry 2", FILE_APPEND);This writes each entry on its own line regardless of the server OSHelpful when creating downloadable text files from web applications4. Defining Constants for Environment-Specific Line Endings
PHP 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.
Use echo "First line" . PHP_EOL . "Second line";PHP_EOL returns on Linux/macOS and on WindowsEnsures consistent behavior when deploying across servers以上就是php输出换行符怎么用_PHP换行符(/r)输出方法教程的详细内容,更多请关注php中文网其它相关文章!



