Writing TXT File with PHP, Want to Add an Actual Line Break

43,572

Solution 1

Sounds to me like you might be using single quotes, i.e. '\n' rather than "\n".

If you wanted to continue with a single quotes bias (as you should!), two options:

file_put_contents('/path/to/file.txt', 'Hello friend!
This will appear on a new line.
As will this');

// or

file_put_contents('/path/to/file.txt', 'Hello friend!'."\n".'This will appear on a new line.'."\n".'As will this');

Solution 2

For "\n" to work, you need to use double quotes, not '\n'.

But you should use the constant PHP_EOL instead, so that it adapts automatically to the OS ("\n", "\r" or "\r\n").

file_put_contents('file.txt', 'Bla' . PHP_EOL . 'Bla');

Solution 3

\r\n in a windows server \n in linux Make sure you upload the file as ASCII.

Solution 4

You must write \n in a double-quoted string (in single-quoted strings no parsing takes place):

"foo\r\nbar"

Further reference:

http://es2.php.net/manual/en/language.types.string.php

Solution 5

you could also use chr(10) which is line break.

Share:
43,572
Chris
Author by

Chris

I work with PHP, MySQL, Objective-C (iPhone), Java (Android), Processing.org & Arduino.

Updated on July 09, 2022

Comments

  • Chris
    Chris almost 2 years

    I am writing a TXT file using PHP. I want to insert actual line breaks into the TXT file wherever necessary. I have tried all combinations of \n \r \r\n \n\r ... but these are not causing any linebreaks to appear - in most cases, I am seeing the text "\n" appear in the TXT file, with no linebreak.

    I have also tried chr(13).

    Any other ideas would be appreciated.

  • Drewdin
    Drewdin over 13 years
    I could not find PHP_EOL on php.net, where can i learn more about what this does? Thanks!
  • Álvaro González
    Álvaro González over 13 years
    Please note that PHP_EOL is the default line ending of the server. It's useful unless you're generating a file for download.