在php中用多行html创建变量


Create variable with multiple lines of html in php

在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; ?> 

您只需要使用"而不是'

$test= "
    <h1>User Ranking</h1>
    <p>$name is ranked number $rank</p>
    <p>lots more info to go in here</p>
";

您可以使用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;

编辑:确保使用双引号