PHP: Creating multiline strings using heredoc <<<

This entry is part 18 of 54 in the series PHP Tutorial

PHP provides another way to create a multiline string using heredoc with the symbol <<<.

Heredoc <<< can be used to echo out HTML code.

In the example below, the HTML_OUTPUT is the identifier used for heredoc.

<?php

echo <<< HTML_OUTPUT
<!DOCTYPE html>
<html>
<head lang='en'>
    <meta charset='UTF-8'>
    <title></title>
</head>
<body>
<header>
    <hgroup>
        <h3>Ushuaia</h3>
        <p>Southernmost city in the world.</p>
    </hgroup>
</header>
</body>
</html>
HTML_OUTPUT;

?>

We can put the entire heredoc string into a variable as below.  I assigned a heredoc to a variable $html_output.

The variable $html_output is then echo out as shown in line 21.

<?php

$html_output = <<< HTML_OUTPUT
<!DOCTYPE html>
<html>
<head lang='en'>
    <meta charset='UTF-8'>
    <title></title>
</head>
<body>
<header>
    <hgroup>
        <h3>Ushuaia</h3>
        <p>Southernmost city in the world.</p>
    </hgroup>
</header>
</body>
</html>
HTML_OUTPUT;

echo $html_output;

?>

I have also made use of heredoc to print out a form in an example in form validation.

Series Navigation<< PHP: String operators
PHP: Arithmetic operators >>

Leave a comment

Leave a Reply