PHP - how to create a newline character?

2019-01-01 17:03发布

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?

13条回答
萌妹纸的霸气范
2楼-- · 2019-01-01 17:23

The "echo" command in PHP sends the output to the browser as raw html so even if in double quotes the browser will not parse it into two lines because a newline character in HTML means nothing. That's why you need to either use:

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

when using "echo", or instead use fwrite...

fwrite([output text]."\n");

This will output HTML newline in place of "\n".

查看更多
流年柔荑漫光年
3楼-- · 2019-01-01 17:25

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.

查看更多
倾城一夜雪
4楼-- · 2019-01-01 17:26

You should use this:

"\n"

You also might wanna have a look at PHP EOL.

查看更多
泛滥B
5楼-- · 2019-01-01 17:29

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

查看更多
唯独是你
6楼-- · 2019-01-01 17:32

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

echo $clientid;
echo ' ';
echo $lastname;
echo ' ';
echo chr (13). chr (10);
查看更多
旧时光的记忆
7楼-- · 2019-01-01 17:33

w3school offered this way:

echo nl2br("One line.\n Another line.");

by use of this function you can do it..i tried other ways that said above but they wont help me..

查看更多
登录 后发表回答