PHP Linefeeds (\n) Not Working - php

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?

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

\n is not meant to be seen as a new line by the end user, you must use the html <br/> element for that.
/n only affects how the html that is generated by php appears in the source code of the web page. if you go to your web page and click on 'view source' you will see php-generated html as one long line. Not pretty. That's what \n is for ; to break that php-generated html into shorter lines. The purpose of \n is to make a prettier 'view source' page.

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.
<?php
echo "Line 1\nLine 2";
?>
This will render in your browser as:
Line 1 Line 2
If you need to send plain text to your browser, you can use something like:
<?php
header('Content-type: text/plain');
echo "Line 1\nLine 2";
?>
This will output:
Line 1
Line 2

nl2br() function use for create new line
echo nl2br("Welcome\r\n This is my HTML document", false);
The above example will output:
Welcome
This is my HTML document

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.

You need to use double quotes. Double quotes have more escape chars.
error_log("test\n", 3, 'error.log');
error_log("test2\n", 3, 'error.log');

to place the \n in double quotes try
$LOG = str_replace('\n', "\n", $LOG);

It's because you use apostrophes ('). Use quotationmarks (") instead. ' prompts PHP to use whatever is in between the apostrophes literally.

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.

The “\n” or “\r” or similar tags are treated as white-space in HTML and browsers. You can use the "pre" tag to solve that issue
<?php
echo "<pre>";
echo "line1 \n some text \t a tab \r some other content";
echo "</pre>";
?>

If you want to print something like this with a newline (\n) after it:
<p id = "theyateme">Did it get eaten?</p>
To print the above, you should do this:
<?php
print('<p id = "theyateme">Did it get eaten?</p>' . "\n");
?>
The client code from above would be:
<p id = "theyateme">Did it get eaten?</p>
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.

Related

escape sequences are not working in php

if im not wrong \n representation means that a newline as <br> .But when i use <br> or another tags they work properly but escape sequences.
example
echo "write somethings<br>";
echo "about coding";
above example works fine but when i try to use escape sequences none of them are not working
echo "write something\n";
echo "about coding";
it's just an example for newline character and the other escaping characters dont work as \n.What is the real logic on this case?
\n and other similar escape sequences are not part of HTML. You should use HTML escape sequences. These can be found here: http://www.theukwebdesigncompany.com/articles/entity-escape-characters.php
So only your <br> tag works but \n is not
No, this is an example of HTML rules.
Putting \n in a PHP string and then outputting it as HTML will put a new line character in the HTML source code. It's just line pressing return when writing raw HTML.
HTML puts no special meaning on the new line character (at least outside of script elements and elements with various non-default values of the CSS white-space property) and treats it like any other white space character.
<br>, on the other hand, is a line break element (but usually an indication that you should be using a block level element around the content instead).
HTML ignores carriage return and linefeed characters, treating them as whitespace. If you want to use display a string formatted with "\n" you can use nl2br to convert it, e.g.
echo nl2br("this is on\ntwo lines");
If you look at this in the browser it wont work : browser knows only HTML for display (<br>) but not escape like \n or \r

How do I let PHP echo "\n" as plain-text for javascript and not have the "\n" create a new line?

PHP is echoing JavaScript (I'm using the jQuery library) something like this:
echo 'var users = $("#add").val().split("\n");';
However, the \n is creating a line break in what the echoed script looks like, and therefore breaking the JavaScript. Is there a way to circumvent this?
Many thanks!
The \n is an escape sequence meaning newline. Backslashes are the beginning of escape sequences, to output a backslash then write \\. So you want \\n. Other useful escape sequences include the quote: use \" to put a quote into the string instead of ending the string.
echo "var users = $(\"#add\").val().split(\"\\n\");";
Not sure If you looking for this
echo "<script>alert('Line1\\\\nThis still in Line1')</script>";

PHP: How to prevent unwanted line breaks

I'm using PHP to create some basic HTML. The tags are always the same, but the actual links/titles correspond to PHP variables:
$string = '<p style="..."><strong><i>'.$title[$i].'</i></strong>
<br>';
echo $string;
fwrite($outfile, $string);
The resultant html, both as echoed (when I view the page source) and in the simple txt file I'm writing to, reads as follows:
<p style="..."><a href="http://www.example.com
"><strong><i>Example Title
</i></strong></a></p>
<br>
While this works, it's not exactly what I want. It looks like PHP is adding a line break every time I interrupt the string to insert a variable. Is there a way to prevent this behavior?
Whilst it won't affect your HTML page at all with the line breaks (unless you are using pre or text-wrap: pre), you should be able to call trim() on those variables to remove newlines.
To find out if your variable has a newline at front or back, try this regex
var_dump(preg_match('/^\n|\n$/', $variable));
(I think you have to use single quotes so PHP doesn't turn your \n into a literal newline in the string).
My guess is your variables are to blame. You might try cleaning them up with trim: http://us2.php.net/trim.
The line breaks show up because of multi-byte encoding, I believe. Try:
$newstring = mb_substr($string_w_line_break,[start],[length],'UTF-8');
That worked for me when strange line breaks showed up after parsing html.

Can't see new lines on textarea - what could the problem be?

I have a php string with a lot of information to be displayed inside a textarea html element.
I don't have access to that textarea nor to the script (if any) that generates it.
$somestring = 'first line \nSecond line \nThird line.';
$somestring as NOT been "worked" with trim or filter_var. Nothing.
On the textfield, I get the \n printed on the textarea hence, not interpreted.
What can I try in order to have those new lines applied?
Thanks in advance.
Try wrapping $somestring with " (double quotes) instead of ' (single quotes)
\n, \r and other backslash escape characters only works in double quotes and heredoc. In single quotes and nowdoc (the single quote version of heredoc), they are read as literal \n and \r.
Example:
<?php
echo "Hello\nWorld"; // Two lines: 'Hello' and 'World'
echo 'Hello\nWorld'; // One line: literally 'Hello\nWorld'
echo <<<HEREDOC
Hello\nWorld
HEREDOC; // Same as "Hello\nWorld"
echo <<<'NOWDOC'
Hello\nWorld
NOWDOC; // Same as 'Hello\nWorld' - only works in PHP 5.3.0+
Read more about this behaviour in the PHP manual
EDIT:
The reason single and double quotes behave differently is because they are both needed in different situations.
For instance, if you would have a string with a lot of new lines, you would use double quotes:
echo "This\nstring\nhas\na\nlot\nof\nlines\n";
But if you would use a string with a lot of backslashes, such as a file name (on Windows) or a regular expression, you would use single quotes to simplify it and avoid having unexpected problems by forgetting to escape a backslash:
echo "C:\this\will\not\work"; // Prints a tab instead of \t and a newline instead of \n
echo 'C:\this\would\work'; // Prints the expected string
echo '/regular expression/'; // Best way to write a regular expression
$somestring = "first line \nSecond line \nThird line.";
http://php.net/types.string <-- extremely useful reading
this article is a cornerstone of PHP knowledge and it's just impossible to use PHP without it.
unlike most of manual pages which are are just for quick reference, this very page is one which every developer should learn by heart.

PHP, why sometimes "\n or \r" works but sometimes doesnt?

Well, I am abit confuse using these \r,\n,\t etc things. Because I read online (php.net), it seems like works, but i try it, here is my simple code:
<?php
$str = "My name is jingle \n\r";
$str2 = "I am a boy";
echo $str . $str2;
?>
But the outcome is "My name is jingle I am a boy"
Either I put the \r\n in the var or in the same line as echo, the outcome is the same. Anyone knows why?
Because you are outputting to a browser, you need to use a <br /> instead, otherwise wrap your output in <pre> tags.
Try:
<?php
$str = "My name is jingle <br />";
$str2 = "I am a boy";
echo $str . $str2;
?>
Or:
<?php
$str = "My name is jingle \n\r";
$str2 = "I am a boy";
echo '<pre>' .$str . $str2 . '</pre>';
?>
Browsers will not <pre>serve non-HTML formatting unless made explicit using <pre> - they are interested only in HTML.
Well in your example you've got \n\r rather than \r\n - that's rarely a good idea.
Where are you seeing this outcome? In a web browser? In the source of a page, still in a web browser? What operating system are you using? All of these make a difference.
Different operating systems use different line terminators, and HTML/XML doesn't care much about line breaking, in that the line breaks in the source just mean "whitespace" (so you'll get a space between words, but not necessarily a line break).
You could also use nl2br():
echo nl2br($str . $str2);
What this function does is replace newline characters in your string to <br>.
Also, you don't need \r, just \n.
In HTML, spaces, tabs, linefeeds and carriage returns are all equivalent white space characters.
In text, historically the following combinations have been used for newlines
\r on Apple Macs
\r\n on Windows
\n on Unix
Either use \n (*NIX) or \r\n (DOS / Windows), \n\r is very uncommon. Once you fix that, it should work just fine.
Of course, if you're outputting HTML, a line break does nothing unless it's inside <pre></pre> tags. Use <br /> to separate lines in HTML. The nl2br() function can help you to convert line breaks to HTML if needed.
Also, if you use single-quoted strings (your example has double quoted strings), \r and \n will not work. The only escape characters available in single quoted strings are \' and \.
Are you displaying the results in an HTML page? if so, HTML strips whitespace like newlines. You'd have to something like use '<br />' instead of '/r/n' in HTML.

Categories