在PHP中写入文本文件时换行不起作用
我有以下测试脚本:在PHP中写入文本文件时换行不起作用,php,fopen,text-files,fwrite,Php,Fopen,Text Files,Fwrite,我有以下测试脚本: <?php $myFile = "testFile.txt"; $fh = fopen($myFile, 'w') or die("can't open file"); $stringData = "Floppy Jalopy\n"; fwrite($fh, $stringData); $stringData = "Pointy Pinto\n"; fwrite($fh, $stringData); fclose($fh); ?> 如果要在Windows记事
<?php
$myFile = "testFile.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = "Floppy Jalopy\n";
fwrite($fh, $stringData);
$stringData = "Pointy Pinto\n";
fwrite($fh, $stringData);
fclose($fh);
?>
如果要在Windows记事本中打开文件,必须使用Windows换行符:\r\n
最好使用PHP\u EOL
。这是跨平台的,因此它会自动为PHP当前运行的平台选择正确的换行符
$stringData = "Floppy Jalopy" . PHP_EOL;
您的代码运行良好
如果您正在Windows上工作,请使用或。内置记事本无法处理Unix样式的行尾。。PHP_EOL;如果你在写字板上打开它,它会像许多其他编辑器一样处理\n
或\r\n
,但是记事本很麻烦。如果文件总是在脚本运行的同一平台上使用,那么最好使用PHP\u EOL
。根据我的经验,大多数情况下,您创建文件以供下载、通过电子邮件发送或稍后解析—所有情况下,您都需要具有特定换行符的文件,而不是脚本恰好运行的平台。这似乎是最佳答案。这似乎是重复的。在我的情况下,这不起作用。公认的答案是有效的+一票