PHP: Heredoc and Nowdoc String Syntax

By Xah Lee. Date: .

heredoc is a string syntax suitable for quoting large text with multiple lines.

start the quote delimiter by

<<<anyLetterSequence

and end it by the same anyLetterSequence , followed by a semicolon, on a line by itself.

<?php

$ss = 9;

$xx = <<<VhswN
i have $ss cats,
and something.
VhswN;

echo $xx;

# i have 9 cats,
# and something.

?>

The output of above is this:

'and what is the use of a book,' thought Alice
'without pictures or conversation?'.

Note that in the above, we used this random string: VhswN for the delimiter. The ending delimiter must be exactly that followed by a semicolon, on a line by itself. No other chars can be there.

Heredoc is especially useful for large block of text (such as a template) that may itself contain many single quotes or double quotes.

Variables inside heredoc will still be interpreted (replaced by their values). Same for escape sequences (For example, {\n, \t, …}).

Nowdoc: Literal Quoting Long Text

To not have variables interpreted, use a form called “nowdoc”. The syntax is the same as heredoc, except you start it like this <<<'anyLetterSequence'. Example:

<?php
$herName = 'Alice';

$longText = <<<'t790151'
'and what is the use of a book,' thought $herName
'without pictures or conversation?'.
t790151;

echo $longText;

The output of above is this:

'and what is the use of a book,' thought $herName
'without pictures or conversation?'.