PHP: Heredoc

Heredoc is an easy way to echo html and Javascript content without having to worry about “‘s or adding ?> <?php all over the place. A simple example is as follows:-

<?php

// Lots of PHP code goes here

$id=57;  // Store the passenger number

$string=<<<END
<span class="blah">Heading</span>
<span>
<select name="project" class="moreBlah" onchange="DoSomething($id);">
END;
echo $string;

// Lots more PHP code goes here

?>

$string will store everything until it gets to the ‘END;’. The ‘END;’ MUST be on a line on its own and must be the first thing on the line.
Also, worth noting that you can just add php variables in place without any additional formatting (see above, just stick a $id in the middle of a Heredoc and it’ll come out as the correct value)
Advertisement

One thought on “PHP: Heredoc”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: