有没有更好的方法来用PHP编写HTML字符串? [英] Is there a better way to write HTML strings in PHP?
问题描述
我发现自己在PHP中编写了很多返回HTML代码的函数.他们可能看起来像这样:
I find myself writing a lot of functions in PHP that return HTML code. They may look something like this:
function html_site_head()
{
return
"
<div id=\"site_header\">
<div id=\"site_header_inner\">
<div id=\"site_header_logo\"></div>
<div id=\"site_header_countdown\">BARE XX DAGER IGJEN</div>
</div>
</div>
";
}
现在我可以发誓,我已经看到了更好的方法来用PHP编写长字符串.我喜欢python的方式:
Now I can swear I've seen better ways to write long strings in PHP. I like python's way of doing it:
return """
<div id="site_header">
<div id="site_header_inner">
<div id="site_header_logo"></div>
<div id="site_header_countdown">BARE XX DAGER IGJEN</div>
</div>
</div>
"""
因为您不必转义引号.一种替代方法是使用单引号,但这意味着不直接在字符串中使用PHP变量.我发誓我已经在PHP中看到过类似的内容:
As you don't have to escape quotation marks. An alternative is using single quotation marks, but that means no using PHP variables directly in the string. I swear I've seen something like this in PHP:
return <<<
<div id="site_header">
<div id="site_header_inner">
<div id="site_header_logo"></div>
<div id="site_header_countdown">BARE XX DAGER IGJEN</div>
</div>
</div>
或类似的东西.有人可以刷新我的记忆吗?
Or something similar. Could someone refresh my memory on this?
谢谢
推荐答案
PHP知道几种声明的语法字符串:
' … '
" … "
<<<DELIMITER
…
DELIMITER
nowdoc语法(自PHP 5.3.0起)
nowdoc syntax (since PHP 5.3.0)
<<<'DELIMITER'
…
DELIMITER
因此,您本身不必使用双引号.
So you don’t have to use the double quotes per se.
这篇关于有没有更好的方法来用PHP编写HTML字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!