488

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?

Damien Flament
  • 1,465
  • 15
  • 27
davidjhp
  • 7,816
  • 9
  • 36
  • 56
  • 2
    possible duplicate of [Print newline in PHP in single quotes](http://stackoverflow.com/questions/2531969/print-newline-in-php-in-single-quotes) – Gordon Nov 21 '10 at 14:54

15 Answers15

753

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

theonlygusti
  • 11,032
  • 11
  • 64
  • 119
Gumbo
  • 643,351
  • 109
  • 780
  • 844
  • So if there's a no-double-quotes policy here, how best to do it with single quoted strings? – Pacerier Oct 18 '14 at 11:08
  • 1
    @Pacerier 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. – Gumbo Oct 18 '14 at 11:12
  • 1
    @Gumbo : 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 '; echo 'New line added'; ?> and seen the output in browser. It literally added new line between two strings I displayed. It means the character
    or
    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.
    – PHPLover Nov 18 '17 at 09:17
  • 1
    @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
    . And of course there is nothing that prevents you from adding '
    ' in a single quoted string. But that does not render a newline in a simple text file.
    – Fencer Mar 12 '19 at 10:26
  • 1
    @Pacerier 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'. – Fencer Mar 12 '19 at 10:29
  • 3
    You should use `PHP_EOL` instead – kurdtpage Jul 18 '19 at 21:22
  • 1
    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. – SherylHohman Feb 28 '20 at 19:28
284

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

Dave Jarvis
  • 30,436
  • 41
  • 178
  • 315
nnevala
  • 5,779
  • 2
  • 20
  • 13
  • 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. – DavidG Jul 31 '22 at 23:27
  • 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 there – kurdtpage Sep 15 '22 at 02:21
117

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.

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
davea0511
  • 1,380
  • 1
  • 8
  • 9
  • 5
    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 HTML – PC3TJ Nov 07 '15 at 04:29
  • 2
    @PC3TJ 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. – Your Common Sense Jul 09 '22 at 16:41
58

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

http://us3.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);
?>
ZygD
  • 22,092
  • 39
  • 79
  • 102
Salvi Pascual
  • 1,788
  • 17
  • 22
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
Damien Flament
  • 1,465
  • 15
  • 27
Kevin S. Miller
  • 913
  • 1
  • 9
  • 21
  • 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 ! – Damien Flament Jun 10 '17 at 21:23
  • @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"` – Kevin S. Miller Jun 11 '17 at 20:47
  • 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. – Damien Flament Jun 13 '17 at 10:31
16

You should use this:

"\n"

You also might wanna have a look at PHP EOL.

Community
  • 1
  • 1
Wouter Dorgelo
  • 11,770
  • 11
  • 62
  • 80
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";
Dirty-flow
  • 2,306
  • 11
  • 30
  • 49
Shoe
  • 74,840
  • 36
  • 166
  • 272
  • 1
    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, `` is anything but valid HTML. – D_4_ni Jul 13 '13 at 10:24
  • 1
    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 (
    )
    – KennyV Feb 18 '14 at 18:43
10

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

echo nl2br("One line.\n Another line.");
Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
amin gholami
  • 453
  • 3
  • 10
  • 1
    The question is not about breaking a line within a paragraph in HTML. It's about the **newline character** ! – Damien Flament Jun 10 '17 at 21:17
  • 1
    For context, the `nl2br()` function converts newline characters to the `
    ` 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.
    – SherylHohman Feb 28 '20 at 19:37
6

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";
Motahar Hossain
  • 567
  • 5
  • 10
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.

theonlygusti
  • 11,032
  • 11
  • 64
  • 119
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.

Community
  • 1
  • 1
Manu R S
  • 872
  • 9
  • 6
  • 1
    The `nl2br` function converts newline characters to the `
    ` 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** !
    – Damien Flament Jun 10 '17 at 21:16
2

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

echo $clientid;
echo ' ';
echo $lastname;
echo ' ';
echo chr (13). chr (10);
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";
youeye
  • 737
  • 1
  • 7
  • 31
1

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

Petter Friberg
  • 21,252
  • 9
  • 60
  • 109
matthewpark319
  • 1,214
  • 1
  • 14
  • 16
0

You Can Try This.
<?php
   $content = str_replace(PHP_EOL, "<br>", $your_content);
 ?>
 
<p><?php echo($content); ?></p>
Tariqul_Islam
  • 527
  • 7
  • 7