We’ve previously discussed how to assign variables and add in variables and all of that good stuff, but what about if you are dealing with a large block of text? There’s many approaches, most that require you to be mindful of escaping characters like simply using quotes to wrap a long string or using implode()
to join a series of array items into a larger string (I commonly do something similar in Javascript since it’s one of the few viable options). PHP provides 2 additional ways to assign / output variables with Here Document and Now Document syntax (more commonly HereDoc and NowDoc).
$copyright = 'Copyright 2013';
echo <<<'HERE'
<h1>Testing out HereDoc Syntax</h1>
<p>Lorem ipsum...</p>
<footer>$copyright</footer>
HERE;
/**
* Output:
* <h1>Testing out HereDoc Syntax</h1>
* <p>Lorem ipsum...</p>
* <footer>$copyright</footer>
*/
echo <<<NOW
<h1>Testing out NowDoc Syntax</h1>
<p>Lorem ipsum...</p>
<footer>$copyright</footer>
HERE;
/**
* Output:
* <h1>Testing out NowDoc Syntax</h1>
* <p>Lorem ipsum...</p>
* <footer>Copyright 2013</footer>
*/
PHPThese two approaches are similar, but as you can see, NowDoc not only uses a quotes string (more typing, albeit not a lot) but it also treats the variables as string literals. In my opinion, HereDoc is the only way to fly since it gives you the best of both worlds, shorter syntax (hey, those 2 extra characters add up!) and the ability to inject variables inside of your string.