针对 PHP 7.3 版本进行编辑:
从 PHP 7.3 版开始,Heredoc 和 Nowdoc 语法变得更加灵活,因此 OP 中的代码现在按原样有效。结束语句的缩进决定了从字符串中删除多少空格。
包含更多信息的官方发布声明:https://www.php.net/manual/en/migration73.new-features.php#migration73.new-features.core.heredoc https://www.php.net/manual/en/migration73.new-features.php#migration73.new-features.core.heredoc
原始答案对 PHP 版本
正如其他人指出的那样,heredoc 语法是严格的,并且结束语句must放置在自己的行上,没有空格。
使用heredoc有非常合理的理由,请参阅这个SO问题例如:在 PHP 中使用 Heredoc 有什么好处? https://stackoverflow.com/questions/5673269/what-is-the-advantage-of-using-heredoc-in-php
如果您是这种情况,那么如果您想保持缩进一致,则将块字符串移动到外部文件(如其他答案所建议的那样)可能是最佳选择。
Heredoc 的替代方案
如果单引号或双引号字符串包含带换行符的文本,则缩进中的所有空格都会保留在输出中,但在浏览器中会被抑制。
根据您想要的输出,您可以编写自己的包装函数,例如,如果您想在浏览器输出中显示换行符:
if( true ) {
if( true ) {
// Single quoted
$single = 'some
text';
echo $single; // some text
// Double quoted
$double = "some
text";
echo $double; // some text
// Custom function
function block($s) {
return preg_replace('/\s*\n\s*/', '<br/>', $s);
}
echo block("some
text"); // some<br/>text
// In a browser this is shown as:
// some
// text
}
}
最后一个例子是block
函数去除换行符周围的所有空格(包括换行符)并将其替换为<br/>
tag.