Line break not working when writing to text file in PHP

54,221

Solution 1

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

Solution 2

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

Solution 3

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.

Share:
54,221
JM4
Author by

JM4

I studied engineering/management of technology but got tossed into the world of web development after working years in a project management capacity. Work with healthcare/insurance companies to develop custom database and reporting solutions along with online enrollment applications.

Updated on May 11, 2020

Comments

  • JM4
    JM4 almost 4 years

    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!

  • Spudley
    Spudley over 13 years
    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.
  • AndreKR
    AndreKR almost 11 years
    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.
  • Herr_Hansen
    Herr_Hansen about 7 years
    This seems to be best answer.
  • Pang
    Pang almost 7 years
    This seems to be repeating this existing answer.
  • Infoconic Technologies
    Infoconic Technologies almost 4 years
    this doesn't work in my case. The accepted answer works. +1 vote