Home > Uncategorized > An Easy Way of Outputting Large Strings in PHP

An Easy Way of Outputting Large Strings in PHP

Another problem I often see with novice PHP developers is that they haven’t discovered the HEREDOC syntax. Most developers pick up tips from the code they take apart which is where I got the HEREDOC syntax from. As it’s also marked up in PHP with <<< you can't google for it when you forget it. So remember: HEREDOC — an alternate way of creating large strings.

$my_var = 'A String';
$my_var = '<p class="intro">A bit of HTML.</p>'; // No need to escape the quotation marks as only apostrophes are used for the string
$my_var = "<p class=\"intro\">A bit of HTML.</p>"; // Need to escape the quotation marks
$my_var = "<p>{$message}</p>"; // Need to escape the quotation marks
$my_var = <<<EOM
<p class="intro">{$message}</p>
EOM;

The HEREDOC syntax works by using <<< followed by a marker. The marker can be anything but it must start on a newline with nothing before it and end with a semi-colon … or it will be missed and you’ll get a parsing error when you try to run the script.

The HEREDOC syntax is particularly useful with large blocks of HTML as you don’t need to escape all of the quotation marks everywhere.

Categories: Uncategorized Tags: ,
  1. No comments yet.
  1. No trackbacks yet.

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

%d bloggers like this: