如何在 PHP 中的 echo 中添加换行符?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12994769/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 04:36:37  来源:igfitidea点击:

How to add a line break within echo in PHP?

php

提问by jumax

I was trying to add a line break for a sentence, and I added /nin following code.

我试图为一个句子添加换行符,并添加/n了以下代码。

echo "Thanks for your email. /n  Your orders details are below:".PHP_EOL;
echo 'Thanks for your email. /n  Your orders details are below:'.PHP_EOL;

For some reasons, the I got server error as the result. How do I fix it?

由于某些原因,结果我收到了服务器错误。我如何解决它?

回答by NullPoiиteя

\nis a line break. /nis not.

\n是换行符。/n不是。



use of \nwith

使用\n

1. echo directly to page

1.直接回显到页面

Now if you are trying to echo string to the page:

现在,如果您尝试将字符串回显到页面:

echo  "kings \n garden";

outputwill be:

输出将是:

kings garden

you won't get gardenin new line because PHP is a server-side language, and you are sending output as HTML, you need to create line breaks in HTML. HTML doesn't understand \n. You need to use the nl2br()function for that.

您不会garden换行,因为 PHP 是一种服务器端语言,并且您将输出作为 HTML 发送,您需要在 HTML 中创建换行符。HTML 不明白\n。您需要为此使用该nl2br()功能。

What it does is:

它的作用是:

Returns string with <br />or <br>inserted before all newlines (\r\n, \n\r, \n and \r).

返回在所有换行符(\r\n、\n\r、\n 和 \r)之前插入<br /><br>插入的字符串。

echo  nl2br ("kings \n garden");

Output

输出

kings
garden

NoteMake sure you're echoing/printing \nin double quotes, else it will be rendered literally as \n. because php interpreter parse string in single quote with concept of as is

注意确保您\n在双引号中回显/打印,否则它将被逐字呈现为 \n。因为 php 解释器以原样的概念解析单引号中的字符串

so "\n" not '\n'

2. write to text file

2.写入文本文件

Now if you echo to text file you can use just \nand it will echo to a new line, like:

现在,如果您回显到文本文件,您可以使用 just\n它会回显到一个新行,例如:

$myfile = fopen("test.txt", "w+")  ;

$txt = "kings \n garden";
fwrite($myfile, $txt);
fclose($myfile);

output will be:

输出将是:

kings
 garden

回答by Maryam Homayouni

You have to use br when using echo , like this :

使用 echo 时必须使用 br ,如下所示:

echo "Thanks for your email" ."<br>". "Your orders details are below:"

and it will work properly

它会正常工作

回答by noetix

The new line character is \n, like so:

新行字符是\n,如下所示:

echo __("Thanks for your email.\n<br />\n<br />Your order's details are below:", 'jigoshop');

回答by Jonathan

You may want to try \r\n for carriage return / line feed

您可能想尝试 \r\n 回车/换行