Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 508
Chris Avatar asked Oct 04 '10 16:10

Chris


People also ask

How to define the linebreaks in a string in PHP?

Define the linebreaks as-it-is in a string. Use the carriage return and newline characters – $lines = "Line 1 Line 2"; Use the PHP_EOL constant – $lines = "Line 1" . PHP_EOL . "Line 2";

How to add line breaks and newlines in PHP?

The common ways to add line breaks and newlines in PHP are: Define the linebreaks as-it-is in a string. Use the carriage return and newline characters – $lines = "Line 1 Line 2"; Use the PHP_EOL constant – $lines = "Line 1" . PHP_EOL . "Line 2"; For HTML, use the <br> tag to add a new line – $lines = "Line 1<br>Line 2";

How to convert HTML <BR> tags to line breaks in PHP?

If you are working with HTML, the nl2br () function will save you a lot of time by automatically converting the line breaks into <br> tags. Unfortunately, PHP does not offer the reverse function to convert HTML <br> tags into line breaks. But thankfully, the “reverse” is as easy as doing a string replacement.

How do I open a file with a line break?

This seems to be best answer. If you want to open the file in Windows notepad, you must use Windows line breaks: if you open it in Wordpad, it'll cope with either or , as will a lot of other editors, but Notepad is fussy.


1 Answers

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');
like image 155
Matthieu Napoli Avatar answered Dec 24 '22 01:12

Matthieu Napoli