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.
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";
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";
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.
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.
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With