Heredoc

Assigning a user defined text label to a variable to hold a string of text, using <<<DELIMITER at the beginning of the assignment and (the same) LABEL followed by a semi-colon ; to identify the end of the string.

 

  • <<< informs PHP that you want to enter heredoc mode
  • DELIMITER can be anything you like, TEXT or anything else could be used
  • Single and Double quotes do not need escaping
  • Variables will be interpolated, i.e. The value of $myVar will be substituted within the string
  • $ should be escaped if you want it displayed, i.e. \$myVar
  • Delimiter DELIMITER; identifies the end of the string. MUST be in the the first column of a new line, with NO spaces around it.
<?php

	$myVar = "London" ;

	$myString = <<<POTATO
		Here's a bunch of text
		Spanning a number of lines for better (code) readability!

		Unfortunately, you'll need to include < br > tags to get a new line!<br>
		<br>
		I'm able to use "double" and 'single' quotes without the need to escape them.
		<br>
		I can use variables within the string, but need to escape the \$ sign
		to display the variable name. For instance, I live in $myVar, used
		the \$myVar defined in the code above.
		<br>
		Finally, you can also use the delimiter (in this case POTATO)
		but only if it's not on a separate line:
POTATO;

	echo $myString ;

?>

*Note: The Delimiter MUST be in the the first column of a new line, with NO spaces around it.

 

 

 

Can also be used without assigning to a var, say if you just wanted to echo it as content:

echo <<< hereDoc
	<ul>
		<li><a href="./">Home</a></li>
		<li><a ref="./send-req.php">Send Request</a></li>
		<li><a href="./server-response.php">Server Response</a></li>
		<li><a href="./events.php">Events</a></li>
		<li><a href="./php-example.php">PHP Example</a></li>
		<li><a href="./mysql.php">AJAX &amp; MySQL</a></li>
		<li><a href="./xml.php">XML</a></li>
	</ul>
hereDoc;

*Note: The Delimiter MUST be in the the first column of a new line, with NO spaces around it.

Leave a Reply