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)

One comment

  1. promahesh · July 27, 2018

    I was not aware of such a useful thing and I have been using echo which made it so difficult to format. Thank you so much!

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 )

Google photo

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

Twitter picture

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

Facebook photo

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

Connecting to %s