PHP 5.4.16(CentOS7)不识别换行符问题求助
嘿,我一眼就揪出问题所在啦——你的heredoc写法犯了两个核心语法错误,直接导致换行完全没生效!
问题根源拆解
PHP的heredoc语法有两个严格要求,你刚好都踩坑了:
- 起始标签
<<<EOT之后必须立刻换行,不能在同一行写任何内容(包括空格和文本)。你代码里把起始标签和内容写在同一行,PHP根本没识别出这是heredoc,只会把它当成普通的字符串拼接。 - 结束标签
EOT必须单独占一行,前后不能有任何空格、缩进或其他字符,甚至连分号都不能跟在同一行。你把结束标签和内容、; ?>挤在一行,同样破坏了heredoc的语法规则。
修正后的正确代码
<?php $name = "MyName"; $foo = new stdClass(); $foo->foo = "Foo"; $foo->bar = [1 => "Bar2"]; echo <<<EOT My name is "$name". I am printing some $foo->foo. Now, I am printing some {$foo->bar[1]}. This should print a capital 'A': \x41 EOT; ?>
额外提醒(针对浏览器输出)
如果是在网页上查看输出,HTML默认会把换行符当成空格处理。要是想让换行在浏览器里显示出来,可以用这两种方式:
- 用
nl2br()函数把换行符转换成HTML的<br>标签:
echo nl2br(<<<EOT My name is "$name". I am printing some $foo->foo. Now, I am printing some {$foo->bar[1]}. This should print a capital 'A': \x41 EOT);
- 把输出包裹在
<pre>标签里,保留原始格式:
echo '<pre>' . <<<EOT My name is "$name". I am printing some $foo->foo. Now, I am printing some {$foo->bar[1]}. This should print a capital 'A': \x41 EOT . '</pre>';
内容的提问来源于stack exchange,提问作者user2236794
相关产品推荐
相关产品推荐

