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, OS 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 1 Line 2”;
- Run the script using filename.php in the terminal
- You will see each string after printed on a new line
2. 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.
一款工业级别的视频增强软件
388 立即学习“”;
- Use echo nl2br(“Line 1 Line 2”);
- This outputs Line 1 followed by a
tag and then Line 2 - The 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 1 Entry 2 “, FILE_APPEND);
- This writes each entry on its own line regardless of the server OS
- Helpful when creating downloadable text files from web lications
4. 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 l 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 Windows
- Ensures consistent behavior when deploying across servers
以上就是输出换行符怎么用_PHP换行符( /r)输出方法教程的详细内容,更多请关注php中文网其它相关文章!
微信扫一扫打赏
支付宝扫一扫打赏
