开发者

Line break not working when writing to text file in PHP

开发者 https://www.devze.com 2023-01-25 15:01 出处:网络
I have the following test script: <?php $myFile = \"testFile.txt\"; $fh = fopen($myFile, \'w\') or die(\"can\'t open file\");

I have the following test script:

<?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);

?>

when run however and opened usign Notepad, the data is returned in a single line without breaks as:

Floppy Jalopy(crazy box)P开发者_运维知识库ointy Pinto(crazy box)

where i cant find the appropriate character for 'crazy box' but its a REALLY crazy box. WHAT GIVES!


It is best to use PHP_EOL. This is cross-platform, so it automatically chooses the correct newline character(s) for the platform PHP is currently running on.

$stringData = "Floppy Jalopy" . PHP_EOL;

PHP Constants


If you want to open the file in Windows notepad, you must use Windows line breaks: \r\n


Your code runs fine.

Use Notepad2 or Notepad++ if you're working on Windows. The built-in Notepad is unable to cope with Unix-style line endings.


. PHP_EOL; will work universally

0

精彩评论

暂无评论...
验证码 换一张
取 消