31

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)Pointy Pinto(crazy box)

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

JM4
  • 6,740
  • 18
  • 77
  • 125

4 Answers4

69

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

Evan Mulawski
  • 54,662
  • 15
  • 117
  • 144
  • 7
    It's only "best" to use `PHP_EOL` if the files are always to be used on the same platform that your script runs on. In my experience most of the time you create files to be downloaded, e-mailed or parsed later - all cases in which you need files with a *specific* newline character and not the one of the platform the script happens to run on. – AndreKR Jul 03 '13 at 20:24
  • This seems to be best answer. – Herr_Hansen Mar 12 '17 at 11:48
36

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

AndreKR
  • 32,613
  • 18
  • 106
  • 168
  • 2
    if you open it in Wordpad, it'll cope with either `\n` or `\r\n`, as will a lot of other editors, but Notepad is fussy. – Spudley Nov 16 '10 at 16:00
1

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.

bcosca
  • 17,371
  • 5
  • 40
  • 51
0

. PHP_EOL; will work universally

swarnim dixit
  • 65
  • 1
  • 4