PHP heredoc and nowdoc
Before talking about heredoc or nowdoc, we need to know that they are different ways to specify a string in PHP. Maybe I should have talked about this topic in the section about variables, but it would be too long for someone to read quickly.
I came up with this post while creating an article about the DOMDocument class in PHP, which is quite long. However, it is designed to help you find what you need to know quickly. I don’t expect anyone to read the entire post.
Heredoc is one of the ways you can delimit a string in PHP. To use heredoc, you must start with <<< followed by an identifier. Then, start a new line and write your string content. Finally, close the string with the same identifier followed by a semicolon on a new line.
It’s similar to using double quotes.
Here is an example syntax:Sintaxis
<?php <<<identificador linea identificador;
Note that identifier; is the delimiter and therefore must be written as one word.
$title = "otra pagina"; $h = <<<HTML <head> <title>$title</title> </head> <!-- blastcoding.com heredoc example --> <body> <h1>$title</h1> este es un texto dentro de body </body> HTML; echo $h;
Nowdoc is very similar to heredoc, except that in the identifier after <<< we use single quotes, the code inside nowdoc will not be parsed in any way, so it will be equivalent to escaping all the code inside it.
It is similar to using single quotes.Sintaxis
<?php <<<'identificador' linea identificador;
Same example, but now using nowdoc :nowdocexample.php
$title = "otra pagina"; $h = <<<'HTML' <head> <title>$title</title> </head> <!-- blastcoding.com nowdoc example --> <body> <h1>$title</h1> este es un texto dentro de body </body> HTML; echo $h;