For example:
$sql = <<<MySQL_QUERY
That's heredoc syntax. You start a heredoc string by putting <<< plus a token of your choice, and terminate it by putting only the token (and nothing else!) on a new line. As a convenience, there is one exception: you are allowed to add a single semicolon after the end delimiter.
Example:
echo <<<HEREDOC
This is a heredoc string.
Newlines and everything else is preserved.
HEREDOC;
This is called a heredoc, and it lets you do a long piece of text that goes over several lines. You can put PHP variables in there and they will replace with the value. The word CHART can be anything. It just needs to be the same to start and stop where the quoted text begins.
You could do the same thing by appending multiple quoted strings, but this is cleaner most of the time for extended documents like this HTML text. There is also something called a nowdoc which is like a single quote string in PHP, but these won't let you use variables inside them.
It is the start of a string that uses the HEREDOC syntax.
A third way to delimit strings is the heredoc syntax: <<<.
After this operator, an identifier is provided, then a newline. The string itself follows, and then the same identifier again to close the quotation.
It's PHP's heredoc.
Example:
$sql = <<<MySQL_QUERY
SELECT *
FROM TAB
WHERE A = 1 AND B = 2
MySQL_QUERY;
It's a heredoc, for long strings that you don't have to worry about quotation marks and whatnot. If you notice the word CHART and then there's a line that says CHART;, that indicates the end of the string.
The important thing to remember when using this format is that whatever string you use to define the end of the string (such as CHART in this case), that word has to appear on a line on its own, followed by a semicolon, and NO characters can occur after the semicolon on the same line, even whitespace, otherwise PHP thinks it's part of the string.
It's the heredoc syntax.
$str = <<<EOD
Example of string
spanning multiple lines
using heredoc syntax.
EOD;
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 Variables
Nowdoc: Is like the '' single quote string no variable are parsed
For the following example I will only show the Heredoc, in order to make a Nowdoc just wrap the token inside single quotes -> 'TOKEN'.
Features and Advantages
The "" and '' can be added as much as needed and won't cause any errror
Easily output HTML code with dynamic variables, avoid usesell concatenations.
Store it in variables for letter use, can create small components and just output them.
The Lines are interpreted literally with '\n' hence is like writing in a doc, also useful to add with nl2br .
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"
Recipes
Use nl2br to add <br> for each line
This 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>
See Task Todos
</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>
See Task Todos
</div>
</div>
</div>
HEREDOC;
$taskRendered .= $component;
}
echo $taskRendered; // Output
?>
Documentation
HEREDOC DOCS
NOWDOW DOCS
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. :)
Related
For example:
$sql = <<<MySQL_QUERY
That's heredoc syntax. You start a heredoc string by putting <<< plus a token of your choice, and terminate it by putting only the token (and nothing else!) on a new line. As a convenience, there is one exception: you are allowed to add a single semicolon after the end delimiter.
Example:
echo <<<HEREDOC
This is a heredoc string.
Newlines and everything else is preserved.
HEREDOC;
This is called a heredoc, and it lets you do a long piece of text that goes over several lines. You can put PHP variables in there and they will replace with the value. The word CHART can be anything. It just needs to be the same to start and stop where the quoted text begins.
You could do the same thing by appending multiple quoted strings, but this is cleaner most of the time for extended documents like this HTML text. There is also something called a nowdoc which is like a single quote string in PHP, but these won't let you use variables inside them.
It is the start of a string that uses the HEREDOC syntax.
A third way to delimit strings is the heredoc syntax: <<<.
After this operator, an identifier is provided, then a newline. The string itself follows, and then the same identifier again to close the quotation.
It's PHP's heredoc.
Example:
$sql = <<<MySQL_QUERY
SELECT *
FROM TAB
WHERE A = 1 AND B = 2
MySQL_QUERY;
It's a heredoc, for long strings that you don't have to worry about quotation marks and whatnot. If you notice the word CHART and then there's a line that says CHART;, that indicates the end of the string.
The important thing to remember when using this format is that whatever string you use to define the end of the string (such as CHART in this case), that word has to appear on a line on its own, followed by a semicolon, and NO characters can occur after the semicolon on the same line, even whitespace, otherwise PHP thinks it's part of the string.
It's the heredoc syntax.
$str = <<<EOD
Example of string
spanning multiple lines
using heredoc syntax.
EOD;
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 Variables
Nowdoc: Is like the '' single quote string no variable are parsed
For the following example I will only show the Heredoc, in order to make a Nowdoc just wrap the token inside single quotes -> 'TOKEN'.
Features and Advantages
The "" and '' can be added as much as needed and won't cause any errror
Easily output HTML code with dynamic variables, avoid usesell concatenations.
Store it in variables for letter use, can create small components and just output them.
The Lines are interpreted literally with '\n' hence is like writing in a doc, also useful to add with nl2br .
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"
Recipes
Use nl2br to add <br> for each line
This 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>
See Task Todos
</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>
See Task Todos
</div>
</div>
</div>
HEREDOC;
$taskRendered .= $component;
}
echo $taskRendered; // Output
?>
Documentation
HEREDOC DOCS
NOWDOW DOCS
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. :)
I'd like to keep my HTML source code pretty and indented (or tabbed). For instance:
$someHTML.='<div class="NOINDENT">';
$someHTML.=' <div class="INDENT1">';
$someHTML.=' <div class="INDENT2"><div>';
$someHTML.=' </div>';
$someHTML.='</div>';
echo $someHTML;
This PHP looks pretty and readable enough to me, but when the HTML is output it will be one long line of code (with no line breaks)! I'd like to have PHP print a line break, but still have the code "readable" while working on it in PHP.
For the above example, is using \n at the end of each line my only option?
Heredoc syntax to the rescue
$someHTML = <<<HTML
<div>
<div>
...
</div>
</div>
HTML;
you can use the constant PHP_EOL to end your lines
$someHTML.='<div class="NOINDENT">'.PHP_EOL;
The HEREDOC syntax is better, but when you are inside functions / loop / etc. which requires tabs, it make the php code looks weird sometimes
I try and avoid echoing html if its more than a single line.
Instead you can use output buffering if you need the html in a string, eg if you need to return a string from a function:
function getHtmlString(){
ob_start(); ?>
<div class="NOINDENT">
<div class="INDENT1">
<div class="INDENT2"><div>
</div>
</div>
<?php
$html = ob_get_clean();
return $html;
}
?>
<html>
<head>...</head>
<body>
<div id="someid">
<?php echo getHtmlString(); ?>
...
Yes, you must add '\n' at the end.
And if you want tabs, add '\t' at the beggining of each line.
In order to use line breaks, you need to use the double-quoted string form and place a newline (\n) character at the end of every line. Note that the double quotes within the string now need to be escaped with a backslash. For example:
$someHTML.="<div class=\"NOINDENT\">\n";
$someHTML.=" <div class=\"INDENT1\">\n";
$someHTML.=" <div class=\"INDENT2\"><div>\n";
$someHTML.=" </div>\n";
$someHTML.="</div>\n";
echo $someHTML;
Another option would be to use the HEREDOC string format, which will maintain whitespace and also has the advantage of not requiring you to escape double quotes:
$someHTML = <<<HERE
<div class="NOINDENT">
<div class="INDENT1">
<div class="INDENT2"><div>
</div>
</div>
HERE;
I wanted to show that this solution is close to what I want , and works great, but the staring and ending ' and '; aren't that pretty. heredoc seems like the best and cleanest answer so far.
function html(){
$someHTML=
'<div class="NOINDENT">a
<div class="INDENT1">b
<div class="INDENT2">c<div>
</div>
</div>';
return $someHTML;
}
echo(html());
I have this variable $url that I need to print inside a quoted HTML that it's inside a PHP if conditional.
<?php
$url = $thumb['0'];
if ( in_category( 'News' )) {
//nothing here
} else {
echo '<div class="image-holder"><img src="$url;" alt="Post photo" class="image-border"></div>';
}
?>
But src="$url;" is interpreted as src="$url;" in the HTML code. It does not interpret as a variable.
How can I solve that?
you can concatenate strings with a dot in php
e.g
echo "This"."is"."a"."sample";
likewise with variables:
echo '<div class="image-holder"><img src="'.$url.'" alt="Post photo" class="image-border"></div>';
When working with strings in PHP, it's important to realize the distinction between single- and double-quoted strings.
Single-quoted strings are basically parsed as literal strings, regardless of what 'special' characters you might use. The only escape sequences are \' for a literal single quote and \\ for a literal backslash. PHP code is treated as simple text, and so are escape sequences like \n (the sequence for a unix newline). This is the format to use for simple string literals like 'Hello World!'.
Double-quoted strings are parsed completely, meaning \n is interpreted as a newline and $var is replaced with the value of the variable $var. So this is much more powerful, but you also have to think more about how your strings will be interpreted. If your interpreted php gets complicated (or is adjacent to non-php that might look like php), you can use braces to clarify your meaning.
Note that there are lots of reasons not to mix strings with php code. Often sprintf, heredoc, or simple concatenation (with .) make things much clearer, as suggested in several other answers.
I like to seperate the business logic from the output. This, in combination with PHP's alternative syntax for control structures, keeps your HTML output clean and easily readable.
See this example:
<?php
// Do some things here
$url = $thumb['0'];
// Below this point we output HTML
// Only use simple control structures here, this keeps your HTML clean and easy to read
?>
<?php if (in_category('News')): ?>
<?php else: ?>
<div class="image-holder"><img src="<?php echo $url; ?>" alt="Post photo" class="image-border">
</div>
<?php endif; ?>
Since the first part of the if-statement is empty, you can simplify the code:
<?php if (!in_category('News')): ?>
<div class="image-holder"><img src="<?php echo $url; ?>" alt="Post photo" class="image-border">
</div>
<?php endif; ?>
Use double quotes and surround your variable in curley braces example
echo "This is my variable. It equals {$var}";
you can do like this
echo '<div class="image-holder"><img src="'.$url.'" alt="Post photo" class="image-border"></div>';
or
echo "<div class='image-holder'><img src='$url' alt='Post photo' class='image-border'></div>";
If you need to work with large portions of HTML and don't want to have to change from double to single quotes [technically disallowed by HTML spec], or escape all of the double quotes [pain in the butt], or constantly drop in and out of <?php ?> tags [ugly, hard to maintain], then use a HEREDOC. eg:
echo <<<_end_
<div class="image-holder"><img src="$url;" alt="Post photo" class="image-border"></div>
_end_;
Variables are expanded, no quotes need escaping, and all of your dreams will come true.
Alternatively, you can stick with a single-quoted string and get cozy with printf() which is a fantastically useful function in its own right. eg:
printf('<div class="image-holder"><img src="%s;" alt="Post photo" class="image-border"></div>', $url);
Do this, (EDIT: simplified code)
<?php
$url = $thumb['0'];
if ( ! in_category( 'News' ) ) {?>
<div class="image-holder">
<img src="<?=$url?>" alt="Post photo" class="image-border" />
</div>
<?}?>
I have this code that is captured in the jquery Data object from a php page.
echo "
var $d = $('<div/>', {
id: 'hi' + $('#textResp').children().length,
class: 'eventdiv',
html: 'hello'
}).hide().fadeIn(3000);
$('#textResp').append($d)
";
Problem is, the 's are not escaped. I have tried using /' to escape, but it comes up with an error. I am sure I am doing this wrong, does anyone know where to put the /' instead of '?
You could use a php nowdoc instead of quotes at all which would simplify things:
echo <<<'DOC'
var $d = $('<div/>', {
id: 'hi' + $('#textResp').children().length,
class: 'eventdiv',
html: 'hello'
}).hide().fadeIn(3000);
$('#textResp').append($d)
DOC;
then use whatever you want inside (quote or dquote). This is, of course, unparsed so if $d was actually referring to a php var then you would have problems.
Your apostrophes actually look fine. But, within a double quoted string, PHP will evaluate any string beginning with a dollar sign as a variable and not produce the desired result. Try replace the jquery related instances of $ with \$. Like this:
echo "
var \$d = \$('<div/>', {
id: 'hi' + \$('#textResp').children().length,
class: 'eventdiv',
html: 'hello'
}).hide().fadeIn(3000);
\$('#textResp').append(\$d)
";
use json_encode function in php, it behaves like the escape_javascript function in rails.
just pass a string argument to the json_encode function, and it return the escaped string for you, see the sample code below:
<?php
$form_html = <<HTML
<form action='...' ...>
<input type='...' name='...' ...>
...
</html>
HTML;
?>
var form_html = <?php echo json_encode($form_html); ?>;
$('.remote#create_form').html(form_html).slideDown();
You will need to use \ before all 's.
However, this is puzzling, why do you feel you need escape characters? It appears you are simply echoing this output, if this is between <script /> tags, you should be fine.
PHP will attempt to expand variables, $name, that occur in strings wrapped in double quotes. Since $d looks like a variable to the PHP interpreter, it will try to replace it with the variable's value.
Assuming that you don't have $d defined anywhere, that will produce an empty space and, possibly, a notice (if you are using error level E_NOTICE).
To prevent that from happening, escape dollar signs with a backslash (replace $ with \$)
Use single quotes for your string construction. Only use double quotes when you specifically are including variables that you want evaluated. PHP is trying to evaluate all of those $ references you have in there. By using single quotes, you will avoid many escaping problems.
echo '
var $d = $("<div/>", {
id: "hi" + $("#textResp").children().length,
class: "eventdiv",
html: "hello"
}).hide().fadeIn(3000);
$("#textResp").append($d)
';
I have a problem with the syntax for a heredoc. Let me show the code first:
function format($user_id,$user_note,$image,$dt){
//this is the problem
if($image=='NULL'){
//don't display image
}
else {
echo '<img src="userpics/$image" width="480" height="480">';
}
return <<<ENDOFRETURN
<div class ="commentbox">
$date
</div>
<div class="leftpanel">
$user_note
$image
<div class="date">
$rel
</div>
</div>
ENDOFRETURN;
}
The $image variable comes from the database, it's either NULL or has a filename. If an image is null I don't want to display the <img> tag, if it does have a value then I want to show it. Do you know how I can solve this problem? I have been trying everything, but nothing has worked yet!! :))
If data in a MySQL database is NULL, you would check that with the is_null() function, not comparing to the string 'NULL':
function format($user_id,$user_note,$image,$dt)
{
if(!is_null($image)){
$image = "<img src=\"userpics/$image\" width=\"480\" height=\"480\">";
}
return <<<ENDOFRETURN
<div class ="commentbox">$date</div>
<div class="leftpanel">
$user_note
$image
<div class="date">$rel</div>
</div>
ENDOFRETURN;
}
Also, as others have mentioned, the end of the heredoc must not be indented.
EDIT: I just edited a few other things in your code and showed the whole function to give you a better idea.
I can see several problems with your code, but where the heredocs syntax is concerned, try removing the spaces before ENDOFRETURN;.
There are several problems, the correct way would be something like:
function format($user_id,$user_note,$image,$dt){
//this is the problem
if($image !== NULL){
$output .= '<img src="userpics/' . $image . '" width="480" height="480">';
}
$output .= <<<ENDOFRETURN
<div class ="commentbox">
$date
</div>
<div class="leftpanel">
$user_note
$image
<div class="date">
$rel
</div>
</div>
ENDOFRETURN;
return $output;
}
you see:
ENDOFRETURN; has no spaces before it
all output is returned in one ... return
For the sake of being thorough:
NULL is a keyword, just like: print, echo, if, for. Meanwhile,'NULL' (note the quotes) is a string, just like if you had typed 'if' (note the quotes, again) it would be a string, not the beginning of an if statement.
Your echo statement in single quotes as above, won't do what you intend it to. The variable $image will not be expanded in a single-quoted string. Reverse your single and double quoting instead as
echo "<img src='userpics/$image' width='480' height='480'>";
Also the ENDOFRETURN; at closing your heredoc must not have any spaces before it.
simply adjust
{spaces or tab}ENDOFRETURN;
to
{no spaces/tab}ENDOFRETURN;
rtm - exactly same problem as yours
It is very important to note that the line with the closing identifier must contain no other characters, except possibly a semicolon (;). That means especially that the identifier may not be indented, and there may not be any spaces or tabs before or after the semicolon. It's also important to realize that the first character before the closing identifier must be a newline as defined by the local operating system. This is \n on UNIX systems, including Mac OS X. The closing delimiter (possibly followed by a semicolon) must also be followed by a newline.
If this rule is broken and the closing identifier is not "clean", it will not be considered a closing identifier, and PHP will continue looking for one. If a proper closing identifier is not found before the end of the current file, a parse error will result at the last line.