James MV
James MV

Reputation: 8727

Outputting variable within Heredoc

I have some html spanning over EOF:

$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;

I've tried single quotes, single quotes with . escaping the double quotes. Can't seem to find the right combination. Any help appreciated.

TIA

Upvotes: 2

Views: 3056

Answers (3)

user3871
user3871

Reputation: 12716

Heredoc is typically used for longer strings, or maybe even multiple thoughts, that you may want segmented on to separate lines.

As tuxradar put it: "In order to allow people to easily write large amounts of text from within PHP, but without the need to constantly escape things, heredoc syntax was developed"

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

In your case, it'd make more sense to simply echo out your string.

$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;

Upvotes: 0

Sammitch
Sammitch

Reputation: 32272

Your code should work, but with Heredocs [which is what this syntax is actually called] you don't usually need to escape anything, or use specific quotes. @showdev's first example hits this.

However, a cleaner, more reusable syntax is found with sprintf().

$email1 = "[email protected]";
$email2 = "[email protected]";

$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/[email protected]">clicking here.</a></p>
<p>Click to remove <a href="http://www.mysite.com/[email protected]">clicking here.</a></p>
*/

Lastly: large, inline style="" declarations really defeat the purpose of CSS.

Upvotes: 1

showdev
showdev

Reputation: 29188

<?php

$email="[email protected]";

$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;

?>

However, from your example, I don't see the purpose of HEREDOC. Why not just:

<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>

Upvotes: 2

Related Questions