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?
I'm pretty sure you are outputting to a html file. The problem is html ignores newlines in source which means you have to replace the newlines with
<br/>
if you want a newline in the resulting page display.Double quotes are what you want. Single quotes ignore the
\
escape. Double quotes will also evaluate variable expressions for you.Check this page in the php manual for more.
You need to use double quotes. Double quotes have more escape chars.
If you want to print something like this with a newline (\n) after it:
To print the above, you should do this:
The client code from above would be:
The output from above would be:
Did it get eaten?
I know it's hard, but I always do it that way, and you almost always have to do it that way.
Sometimes you want PHP to print \n to the page instead of giving a newline, like in JavaScript code (generated by PHP).
NOTE about answer: You might be like: Why did you use print instead of echo (I like my echo). That is because I prefer print over echo and printf, because it works better in some cases (my cases usually), but it can be done fine with echo in this case.
When you run a PHP script in a browser, it will be rendered as HTML by default. If the books you’re using show otherwise, then either the code or the illustration is inaccurate. You can use “view source” to view what was sent to the browser and you’ll see that your line feeds are present.
This will render in your browser as:
If you need to send plain text to your browser, you can use something like:
This will output:
Use double quotes.
"test\n"
will work just fine.http://php.net/manual/en/language.types.string.php