在perl中我可以qq []将多行html放入变量中,如下所示。
PERL
my $rank = 1;
my $name = 'John';
sub writeMsg
{
$test = qq[
<h1>User Ranking</h1>
<p>$name is ranked number $rank</p>
<p>lots more info to go in here</p>
];
return $test;
}
print writeMsg($rank, $name);
在php中,我似乎找不到办法做到这一点? 我在下面的解决方案返回相同的结果,但它已经很难阅读并保持语法正确,
PHP
$rank=1;
$name = 'John';
function writeMsg($rank, $name) {
$test = '<h1>User Ranking</h1>' . $name . ' is ranked number ' . $rank ' <p>lots more info to go in here</p>';
return $test;
}
print writeMsg($rank, $name);
有没有办法在PHP中执行此操作?我熟悉使用以下语法在foreach中做类似的事情,但是还没有能够为变量做出这样的好方法吗?
<?php foreach ($get_tests as $test): ?>
<?php endforeach; ?>
答案 0 :(得分:4)
您可以使用heredoc(http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc):
<?php
$str = <<<"EOD"
<p>Example of string</p>
<b>spanning multiple lines</b>
<p>using nowdoc syntax.</p>
EOD;
echo $str;
编辑:确保使用双引号
答案 1 :(得分:3)
您只需使用"
代替'
$test= "
<h1>User Ranking</h1>
<p>$name is ranked number $rank</p>
<p>lots more info to go in here</p>
";