Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Linefeeds (\n) Not Working

Tags:

php

newline

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?

like image 678
ggutenberg Avatar asked Jun 10 '10 15:06

ggutenberg


People also ask

Does \n work in PHP?

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.

How do I add a new line to a string in PHP?

The nl2br() function inserts HTML line breaks (<br> or <br />) in front of each newline (\n) in a string.

What is the \n in PHP?

\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.

What does br /> mean in PHP?

<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.


1 Answers

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

like image 94
ceejayoz Avatar answered Sep 24 '22 02:09

ceejayoz