PHP - how to create a newline character?
Asked Answered
C

16

490

In PHP I am trying to create a newline character:

echo $clientid;
echo ' ';
echo $lastname;
echo ' ';
echo '\r\n';

Afterwards I open the created file in Notepad and it writes the newline literally:

1 John Doe\r\n 1 John Doe\r\n 1 John Doe\r\n

I have tried many variations of the \r\n, but none work. Why isn't the newline turning into a newline?

Chapland answered 21/11, 2010 at 14:47 Comment(1)
possible duplicate of Print newline in PHP in single quotesAristocrat
H
761

Only double quoted strings interpret the escape sequences \r and \n as '0x0D' and '0x0A' respectively, so you want:

"\r\n"

Single quoted strings, on the other hand, only know the escape sequences \\ and \'.

So unless you concatenate the single quoted string with a line break generated elsewhere (e. g., using double quoted string "\r\n" or using chr function chr(0x0D).chr(0x0A)), the only other way to have a line break within a single quoted string is to literally type it with your editor:

$s = 'some text before the line break
some text after';

Make sure to check your editor for its line break settings if you require some specific character sequence (\r\n for example).

Hawkinson answered 21/11, 2010 at 14:48 Comment(7)
So if there's a no-double-quotes policy here, how best to do it with single quoted strings?Incorruption
@Incorruption The only way to have carriage return and new line characters in a single quoted string is entering the characters directly via keyboard (press Enter, depending on your editor’s settings on line endings). Otherwise just use string concatenation.Hawkinson
@Hawkinson : You are saying Single quoted strings, on the other hand, only know the escape sequences \\ and \'. But I just printed a line with echo as <?php echo 'You are using Internet Explorer.<br>'; echo 'New line added'; ?> and seen the output in browser. It literally added new line between two strings I displayed. It means the character <br> or <br/> gets expand in single quoted string. Are there any other such HTML characters apart from these three that can be understood by PHP inside the single quoted strings? I kindly request you to update your answer accordingly. Thank You.Reduced
@user2839497 What you are saying does not make any sense. There's no browser context here. And of course the browser renders a newline when encountering a <br/>. And of course there is nothing that prevents you from adding '<br/>' in a single quoted string. But that does not render a newline in a simple text file.Mediative
@Incorruption For a single quote policy instead of linebreaking the string in the editor like Gumbo suggested in his comment you could use the other solution in Gumbos answer, example: 'outputting a newline'.chr(0x0A).'in a single quoted string'.Mediative
You should use PHP_EOL insteadGradin
Not the "only other way". PHP actually defines a constant specifically for this purpose, that is guaranteed to work, no matter the platform or OS. PHP_EOL. Otherwise a good answer, referencing many of the options and pitfalls.Electrolyte
P
289

Use the predefined PHP_EOL constant:

echo $clientid, ' ', $lastname, PHP_EOL;

The constant value will be set according to the line endings of the operating system where PHP is executing. On Linux, it will be "\n"; on Windows, it will be "\r\n".

Phalanx answered 21/11, 2010 at 14:50 Comment(2)
I could not get newline to work in the php sandbox I'm using so I tried PHP_EOL. Worked like a charm. Thanks. Guess it runs on Windows server.Deuteron
This should be the accepted answer. I still don't know why people keep using \r\n. I mean, I know Windows is the most common OS, but cmon guys, there ARE other OS's out thereGradin
C
118

The browser will not parse linefeeds into two lines because a newline character in HTML means nothing. That's why when needs a new line in HTML, one has to add some tag, <br> being the simplest one:

echo [output text]."<br>\n";

This will output the HTML newline.

Note that it's a good idea to add a new line anyway, so you'll have readable HTML when checking the page source.

Cauterize answered 23/12, 2013 at 18:50 Comment(2)
With the way the question is asked it is likely that he is outputing this data to either a textbox or javascript, etc. for parsing or plain text reading not to be rendered as HTMLDaggna
@Daggna when a million users come for the answer from Google, the way the initial question was asked becomes the least important thing in the universe.Locker
L
59

Use the constant PHP_EOL to get the right character no matter the platform.

https://www.php.net/manual/en/reserved.constants.php

A simple usage example:

<?php
$data = 'First line' . PHP_EOL .
        'Second line' . PHP_EOL .
        'Third line';

file_put_contents("filename.txt", $data);
?>
Lizbeth answered 4/1, 2015 at 6:0 Comment(0)
B
25

Strings between double quotes "" interpolate, meaning they convert escaped characters to printable characters.

Strings between single quotes '' are literal, meaning they are treated exactly as the characters are typed in.

You can have both on the same line:

echo '$clientid $lastname ' . "\r\n";
echo "$clientid $lastname \r\n";

outputs:

$clientid $lastname
1 John Doe
Biophysics answered 21/11, 2012 at 20:7 Comment(3)
Your explanation about the different types of string notations in PHP is fine as it shows the error made by the question author. But your code sample will not produce the expected result as the variables are used in a single quoted string and, as you mentioned, they will not be interpolated !Diplocardiac
@Damien Flament, That's what I said - the contents between single quotes are not interpolated, but the contents between the double quotes are. Perhaps my example is confusing because you are expecting to see the contents of $clientid and $lastname, rather than the literals "$clientid" and "$lastname". I think this was the heading of a table that I used during debugging. the following lines would have been echo "$clientid $lastname\r\n"Biophysics
When writing "the expected result", I'm talking about the result the question author expected in its question. Adding the code shown on your comment to your answer and showing the result might improve your answer quality.Diplocardiac
F
16

You should use this:

"\n"

You also might wanna have a look at PHP EOL.

Finesse answered 21/11, 2010 at 14:49 Comment(0)
P
14

Actually \r\n is for the html side of the output. With those chars you can just create a newline in the html code to make it more readable:

echo "<html>First line \r\n Second line</html>";

will output:

<html>First line
Second line</html>

that viewing the page will be:

First line Second line

If you really meant this you have just to fix the single quote with the "" quote:

echo "\r\n";

Otherwise if you mean to split the text, in our sample 'First line' and 'Second line' you have to use the html code: <br />:

First line<br />Second line

that will output:

First line
Second line

Also it would be more readable if you replace the entire script with:

echo "$clientid $lastname \r\n";
Pantsuit answered 21/11, 2010 at 14:52 Comment(2)
No, it shouldn't. Because it's mostly wrong. The first code block will render as First line Second line - any whitespace including newlines will compress to one space character in the rendered output. Also, </br> is anything but valid HTML.Carolanncarole
Also keep in mind if you are sending out text emails with your php script, you will still need those line endings instead of breaks (<br>)Gavra
C
11

There is a handy PHP function for HTML output that adds a <br /> tag to new lines:

echo nl2br("One line.\n Another line.");
Class answered 16/8, 2015 at 10:26 Comment(2)
The question is not about breaking a line within a paragraph in HTML. It's about the newline character !Diplocardiac
For context, the nl2br() function converts newline characters to the <br /> HTML tag. This might be useful for creating a newline on browser pages, but not a newline in text files, or JavaScript, or printing to the screen or console.Electrolyte
P
5

Nothing was working for me.

PHP_EOL

. "\r\n";

$NEWLINE_RE = '/(\r\n)|\r|\n/'; // take care of all possible newline-encodings in input file
$var = preg_replace($NEWLINE_RE,'', $var);

Works for me:

$admin_email_Body = $admin_mail_body .'<br>' ."\r\n";
$admin_email_Body .= 'This is line 2 <br>' ."\r\n";
$admin_email_Body .= 'This is line 3 <br>' ."\r\n";
Paraphrase answered 4/1, 2020 at 4:34 Comment(4)
this is html page context. Original question is about writing to file. I guessEmalia
A newline character in PHP not a break in HTMLOfficialese
There was literally a dozen answers suggesting the same. How come none worked for you? And what's the point of the first code snippet? It doesn't add, it removes the new line character.Locker
I don't understand why this answer (which does not attempt to resolve the asked question) has a positive score. /(\r\n)|\r|\n/ can be boiled down to /\R/. This unrefined answer is posted on the wrong page. See: https://mcmap.net/q/75442/-how-to-remove-new-lines-and-returns-from-php-stringAdenoma
G
4

For some reason, every single post asking about newline escapes in PHP fails to mention the case that simply inserting a newline into single-quoted strings will do exactly what you think:

ex 1.

 echo 'foo\nbar';

Example 1 clearly does not print the desired result, however, while it is true you cannot escape a newline in single-quotes, you can have one:

ex 2.

 echo 'foo
 bar';

Example 2 has exactly the desired behavior. Unfortunately the newline that is inserted is operating system dependent. This usually isn't a problem, as web browsers/servers will correctly interpret the newline whether it is \r, \r\n, or \n.

Obviously this solution is not ideal if you plan to distribute the file through other means then a web browser and to multiple operating systems. In that case you should see one of the other answers.

note: using a feature rich text editor you should be able to insert a newline as a binary character(s) that represents a newline on a different operating system than the one editing the file. If all else fails, simply using a hex editor to insert the binary ascii character would do.

Grefe answered 12/7, 2013 at 4:41 Comment(0)
R
3

Use the PHP nl2br to get the newlines in a text string..

$text = "Manu is a good boy.(Enter)He can code well.

echo nl2br($text);

Result.

Manu is a good boy.

He can code well.

Rentsch answered 29/10, 2013 at 19:2 Comment(1)
The nl2br function converts newline characters to the <br /> HTML tag. If the string does not contains any newline character, this function will do nothing ! Moreover the question is not about breaking a line within a paragraph in HTML. It's about the newline character !Diplocardiac
I
2

Use chr (13) for carriage return and chr (10) for new line

echo $clientid;
echo ' ';
echo $lastname;
echo ' ';
echo chr (13). chr (10);
Iridosmine answered 5/6, 2013 at 9:10 Comment(0)
K
1

I have also tried this combination within both the single quotes and double quotes. But none has worked. Instead of using \n better use <br/> in the double quotes. Like this..

$variable = "and";
echo "part 1 $variable part 2<br/>";
echo "part 1 ".$variable." part 2";
Kimberlite answered 10/4, 2013 at 7:13 Comment(1)
The question is not about breaking a line within a paragraph in HTML. It's about the newline character !Diplocardiac
R
1

For any echo statements, I always use <br> inside double quotes.

Rombert answered 15/2, 2017 at 20:13 Comment(1)
The question is not about breaking a line within a paragraph in HTML. It's about the newline character !Diplocardiac
A
-1
<?php
    $content = str_replace(PHP_EOL, "<br>", $your_content);
?>
<p><?php echo($content); ?></p>
Assumptive answered 29/10, 2019 at 16:12 Comment(0)
I
-1

It worked for me.

'New' . nl2br(chr(10)) . 'string'.
Insensibility answered 17/4 at 17:13 Comment(1)
What is "it"? Can you share some explanation such that others can learn from it?Lenardlenci

© 2022 - 2024 — McMap. All rights reserved.