For some reason I can't use \n
to create a linefeed when outputting to a file with PHP. It just writes "\n
" to the file. I've tried using "\\n
" as well, where it just writes "\n" (as expected). But I can't for the life of me figure out why adding \n to my strings isn't creating new lines. I've also tried \r\n
but it just appends "\r\n
" to the line in the file.
Example:
error_log('test\n', 3, 'error.log'); error_log('test2\n', 3, 'error.log');
Outputs:
test\ntest2\n
Using MAMP on OSX in case that matters (some sort of PHP config thing maybe?).
Any suggestions?
Answer: Use the Newline Characters ' \n ' or ' \r\n ' You can use the PHP newline characters \n or \r\n to create a new line inside the source code. However, if you want the line breaks to be visible in the browser too, you can use the PHP nl2br() function which inserts HTML line breaks before all newlines in a string.
The nl2br() function inserts HTML line breaks (<br> or <br />) in front of each newline (\n) in a string.
\n is the newline or linefeed, other side \r is the carriage return. They differ in what uses them. Windows uses \r\n to signify the enter key was pressed, while Linux and Unix use \n to signify that the enter key was pressed.
<br /> is a HTML line-break, whereas \n is a newline character in the source code. In other words, <br /> will make a new line when you view the page as rendered HTML, whereas \n will make a new line when you view the source code.
Use double quotes. "test\n"
will work just fine (Or, use 'test' . PHP_EOL
).
If the string is enclosed in double-quotes ("), PHP will interpret more escape sequences for special characters:
http://php.net/manual/en/language.types.string.php
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