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

Chris picture Chris · Oct 4, 2010 · Viewed 41.5k times · Source

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.

Answer

Matthieu Napoli picture Matthieu Napoli · Oct 4, 2010

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