php echo中的\n或\n不打印
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13741485/
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
\n or \n in php echo not print
提问by Albi Hoti
Possible Duplicate:
Print newline in PHP in single quotes
Difference between single quote and double quote string in php
$unit1 = 'paragrahp1';
$unit2 = 'paragrahp2';
echo '<p>' . $unit1 . '</p>\n';
echo '<p>' . $unit2 . '</p>';
This is displaying (on view source):
这是显示(在查看源代码上):
<p>paragraph1</p>\n<p>paragraph2</p>
but isnt what I'm expecting, not printing the new line, what can be?
但不是我所期望的,不打印新行,可以是什么?
回答by Tom van der Woerdt
PHP only interprets escaped characters (with the exception of the escaped backslash \\and the escaped single quote \') when in double quotes (")
PHP 仅在双引号 ( ) 中解释转义字符(转义反斜杠\\和转义单引号\'除外")
This works (results in a newline):
这有效(导致换行):
"\n"
This does not result in a newline:
这不会导致换行:
'\n'
回答by Kafoso
Better use PHP_EOL ("End Of Line") instead. It's cross-platform.
最好改用 PHP_EOL(“行尾”)。它是跨平台的。
E.g.:
例如:
$unit1 = 'paragrahp1';
$unit2 = 'paragrahp2';
echo '<p>' . $unit1 . '</p>' . PHP_EOL;
echo '<p>' . $unit2 . '</p>';
回答by Salman A
Escape sequences (and variables too) work inside double quotedand heredocstrings. So change your code to:
转义序列(以及变量)在双引号和heredoc字符串中起作用。因此,将您的代码更改为:
echo '<p>' . $unit1 . "</p>\n";
PS: One clarification, single quotes strings do accept two escape sequences:
PS:澄清一下,单引号字符串确实接受两个转义序列:
\'when you want to use single quote inside single quoted strings\\when you want to use backslash literally
\'当您想在单引号字符串中使用单引号时\\当你想从字面上使用反斜杠时
回答by ma?ek
\nmust be in double quotes!
\n必须是双引号!
echo "hello\nworld";
Output
输出
hello
world
A nice way around this is to use PHP as a more of a templating language
解决这个问题的一个好方法是将 PHP 用作更多的模板语言
<p>
Hello <span><?php echo $world ?></span>
</p>
Output
输出
<p>
Hello <span>Planet Earth</span>
</p>
Notice, all newlines are kept in tact!
请注意,所有换行符都保持原样!
回答by NullPoiиteя
\nmust be in double quotes!
\n必须是双引号!
echo '<p>' . $unit1 . "</p>\n";
回答by vaibhav
$unit1 = "paragrahp1";
$unit2 = "paragrahp2";
echo '<p>'.$unit1.'</p>';
echo '<p>'.$unit2.'</p>';
Use Tag <p>always when starting with a new line so you don't need to use /n type syntax.
<p>以新行开头时始终使用 Tag ,因此您无需使用 /n 类型语法。

