For example:
$sql = <<<MySQL_QUERY
I found both Heredoc and Nowdoc extremelly powerfull and usefull in PHP and I am surprise that no one have so far give more example of what you can do.
First the difference between Heredoc and Nowdoc is simple,
Heredoc: Is like the "" double quote string you can put VariablesNowdoc: Is like the '' single quote string no variable are parsedFor the following example I will only show the Heredoc, in order to make a Nowdoc just wrap the token inside single quotes -> 'TOKEN'.
Simple Example
$a = "Hello";
$b = "World";
// HEREDOC
echo <<<HEREDOC
<strong> HEREDOC: </strong>
Variable A: "$a"
Variable B: "$b"
HEREDOC;
echo '</br>';
// NOWDOC
echo <<<'NOWDOC'
<strong> NOWDOC: </strong>
Variable A: "$a"
Variable B: "$b"
NOWDOC;
output
HEREDOC: Variable A: "Hello" Variable B: "World"
NOWDOC: Variable A: "$a" Variable B: "$b"
<br> for each lineThis works because HEREDOC interpretes each \n as an actual line
// HEREDOC
echo nl2br(<<<HEREDOC
<strong> HEREDOC: </strong>
Variable A: "$a"
Variable B: "$b"
HEREDOC);
// Output HEREDOC:
//Variable A: "Hello"
//Variable B: "World"
Create small components
<?php
foreach($tasks as $task) {
// Create an HTML like component
$component = <<<HEREDOC
<div class="pure-u-1-3">
<div class="card">
<div class="card-header">
{$task['name']}
</div>
<div class="card-body">
<h5 class="card-title"> {$task['state']} </h5>
<p class="card-text"> {$task['description']} </p>
<a href="view?model=todo_list&task_id={$task['id']}" class="btn btn-primary">See Task Todos</a>
</div>
</div>
</div>
HEREDOC;
echo $component; // Output
}
?>
Or just put in one string then output with 1 echo
<?php
$taskRendered = '';
foreach($tasks as $task) {
// Create an HTML like component
$component = <<<HEREDOC
<div class="pure-u-1-3">
<div class="card">
<div class="card-header">
{$task['name']}
</div>
<div class="card-body">
<h5 class="card-title"> {$task['state']} </h5>
<p class="card-text"> {$task['description']} </p>
<a href="view?model=todo_list&task_id={$task['id']}" class="btn btn-primary">See Task Todos</a>
</div>
</div>
</div>
HEREDOC;
$taskRendered .= $component;
}
echo $taskRendered; // Output
?>
To get a clear idea:
$data = array(
"Id" => 12345,
"Cutomer" => "hi",
"Quantity" => 2,
"Price" => 45
);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
If we use <<<:
$data = <<<DATA
{
"Id": 12345,
"Customer": "John Smith",
"Quantity": 1,
"Price": 10.00
}
DATA;
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
Conclusion: If we go with the 1st method we have to convert it into json_encode() which somehow requires some processing. Instead, We can use the <<< operator to save some time and get some clean code. :)