Heredoc中的输出变量


Outputting variable within Heredoc

我有一些横跨EOF的html:

$message = <<<EOF
<p style="font-size: 9px; font-family: Verdana, Helvetica; width: 100%; text-align:left;">Clcik to remove <a href="http://www.mysite.com/remove.php?email=' $email '">clicking here.</a></p>
EOF;

我试过单引号,单引号。转义双引号。似乎找不到合适的组合。感谢任何帮助。

TIA

<?php
$email="test@example.com";
$message = <<<EOF
<p style="font-size: 9px; font-family: Verdana, Helvetica; width: 100%; text-align:left;">Click to remove <a href="http://www.mysite.com/remove.php?email=$email">clicking here.</a></p>
EOF;
echo $message;
?>

然而,从你的例子中,我看不出HEREDOC的目的。为什么不直接:

<p style="font-size: 9px; font-family: Verdana, Helvetica; width: 100%; text-align:left;">Click to remove <a href="http://www.mysite.com/remove.php?email=<?=$email?>">clicking here.</a></p>

您的代码应该工作,但使用Heredocs[这是该语法的实际名称],您通常不需要转义任何内容,或使用特定的引号。@showdev的第一个例子就是这样。

然而,在sprintf()中发现了一种更清晰、更可重用的语法。

$email1 = "bill@example.com";
$email2 = "ted@example.com";
$message_frame = '<p>Click to remove <a href="http://www.mysite.com/remove.php?email=%s">clicking here.</a></p>';
$message .= sprintf($message_frame, $email1);
$message .= sprintf($message_frame, $email2);
/* Output:
<p>Click to remove <a href="http://www.mysite.com/remove.php?email=bill@example.com">clicking here.</a></p>
<p>Click to remove <a href="http://www.mysite.com/remove.php?email=ted@example.com">clicking here.</a></p>
*/

最后:大的、内联的style=""声明确实违背了CSS的目的。

Heredoc通常用于较长的字符串,甚至可能是多个想法,您可能希望将其分割为单独的行。

正如tuxradar所说:"为了允许人们在PHP中轻松编写大量文本,而不需要经常转义,开发了heredoc语法"

<?php
$mystring = <<<EOT
    This is some PHP text.
    It is completely free
    I can use "double quotes"
    and 'single quotes',
    plus $variables too, which will
    be properly converted to their values,
    you can even type EOT, as long as it
    is not alone on a line, like this:
EOT;
?> 

在您的情况下,简单地回显字符串会更有意义。

$message = '<p style="font-size: 9px; font-family: Verdana, Helvetica; width: 100%; text-align:left;">Clcik to remove <a href="http://www.mysite.com/remove.php?email=' $email '">clicking here.</a></p>';
echo $message;