PHP中实现换行的两种方法:使用跨平台的PHP_EOL常量,代表当前平台的换行符。使用通用的\n字符,表示新的一行。

PHP中换行的实现
在PHP中,换行可以使用以下两种方法实现:
1. PHP_EOL 常量
PHP_EOL 常量代表当前平台的换行符。它可以跨平台使用,无论操作系统如何。
立即学习“PHP免费学习笔记(深入)”;
<code class="php">echo 'Hello world!' . PHP_EOL;</code>
2. \n 字符
\n 字符表示新的一行。它在所有平台上都可用,但不如 PHP_EOL 常量灵活。
<code class="php">echo 'Hello world!\n';</code>
示例:
以下代码片段使用 PHP_EOL 常量将文本写入文件,并在每一行之后添加一个换行符:
<code class="php"><?php
$file = fopen('test.txt', 'w');
fwrite($file, 'This is line 1.' . PHP_EOL);
fwrite($file, 'This is line 2.' . PHP_EOL);
fwrite($file, 'This is line 3.' . PHP_EOL);
fclose($file);
?></code>输出:
<code>This is line 1. This is line 2. This is line 3.</code>











