For text that runs over many lines, such as an email body or a block of HTML, quotes get messy. Heredoc and nowdoc are made for this.
Heredoc: like double quotes
A heredoc starts with <<< and a name (the marker). It ends when the same name appears again on its own line.
<?php
$name = "Priya";
$order = 1042;
echo <<<TEXT
Hello $name,
Your order #$order has shipped.
Thank you!
TEXT;
Hello Priya,
Your order #1042 has shipped.
Thank you!
Variables are replaced, and quotes inside need no escaping.
Nowdoc: like single quotes
A nowdoc looks the same, but the marker is wrapped in single quotes. Nothing is replaced.
<?php
echo <<<'CODE'
Use $name to print the name.
Line two: \n is not a new line here.
CODE;
Use $name to print the name.
Line two: \n is not a new line here.
Nowdoc is handy for showing code samples and templates.
Indented closing marker
Since PHP 7.3 you may indent the closing marker. PHP then removes that same indentation from every line, so you can keep the code tidy.
<?php
function welcome(string $name): string
{
return <<<HTML
<h1>Welcome, $name</h1>
<p>Glad you are here.</p>
HTML;
}
echo welcome("Priya");
<h1>Welcome, Priya</h1>
<p>Glad you are here.</p>
The closing HTML; has 8 spaces, so 8 spaces are removed from each line above it.
Rules
- The opening line is
<<<MARKERwith nothing after it. - The closing marker must be alone on its line (it can be indented). A
;or,can follow it. - Every line of the text must be indented at least as far as the closing marker.
Expressions
You can use {$var} and {$array['key']} just like in double quotes.
<?php
$user = ["name" => "Priya", "role" => "admin"];
echo <<<INFO
Name: {$user['name']}
Role: {$user['role']}
INFO;
Name: Priya
Role: admin