<?php
$output = 'This is line 1' . PHP_EOL .
'This is line 2' . PHP_EOL .
'This is line 3';
$file = "filename.txt";
if (is_writable($file)) {
// In our example we're opening $file in append mode.
// The file pointer is at the bottom of the file hence
// that's where $output will go when we fwrite() it.
if (!$handle = fopen($file, 'a')) {
echo "Cannot open file ($file)";
exit;
}
// Write $output to our opened file.
if (fwrite($handle, $output) === FALSE) {
echo "Cannot write to file ($file)";
exit;
}
echo "Success, content ($output) wrote to file ($file)";
fclose($handle);
} else {
echo "The file $file is not writable";
}
?>
我完全不建议使用PHP_EOL。Unix/Linux使用\n, MacOS / OS X也从\r改为\n,在Windows上,许多应用程序(特别是浏览器)也可以正确显示它。在Windows上,更改现有的客户端代码仅使用\n并保持向后兼容性也很容易:只需将行切边的分隔符从\r\n更改为\n,并将其包装在类似trim()的函数中。