Here Document

Something that you may not know about PHP and many other languages is that it provides heredoc syntax to build strings. What does this mean? Check out the following:

$title = 'Test HTML Page';
$myCode = <<<STR
<html>
  <head>
    <title>$title</title>
  </head>
  <body>
    <h1>$title</h1>
    <p>This is a test page to show that "heredoc" syntax in PHP actually works.</p>
  </body>
</html>
STR;

The above puts the following into the $myCode variable as a string:

<html>
  <head>
    <title>Test HTML Page</title>
  </head>
  <body>
    <h1>Test HTML Page</h1>
    <p>This is a test page to show that "heredoc" syntax in PHP actually works.</p>
  </body>
</html>

You can use this syntax in many different languages:

  • Bash
  • C++
  • Lua
  • Perl
  • PHP
  • Python
  • R
  • Racket
  • Ruby
  • Tcl

There are other languages that also support this syntax as well but I think it is important to note that neither Java nor JavaScript support this syntax.  For more information, you can check out the Wikipedia page.

Leave a Reply

Your email address will not be published. Required fields are marked *


four − 4 =

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="">