PHP: HeredocsLocation: Articles > PHP > Here Do you find it annoying to output HTML and face the problem where the HTML uses attributes and the values are dependant on PHP variables? Heredocs provides an effective way to assign data to a variable without the need for escaping quotes whilst maintaining the ability to use variables. Table of ContentsExample Scenario
<?php
$item_costs = array( 'apple' => 2 , 'banana' => 3 , 'carrot' => 5 ); foreach( $item_costs as $k => $v ){ echo "<td class=\"itemname\">{$k}s</td> "; echo "<td class=\"price\">{$v}/kg</td> "; } ?> As you can see that is a simple example using simple variables and the only inconvenience is the quotation marks around the attribute values. But hopefully, you understand that this can get complex when you introduce data submitted from a form, variable dependant properties, JavaScript and so on. Just a note, some readers may notice that a single quote (') can be used for the attribute values. I don't recommend this and it is better to stay consistent. The usage of double quotes (") is more widely used and accepted. What are heredocs?Heredocs is a PHP syntax that replaces the need to enclose strings in quotes. The example shown below is the heredocs alternative to the example scenario above.
<?php
$item_costs = array( 'apple' => 2 , 'banana' => 3 , 'carrot' => 5 ); foreach( $item_costs as $k => $v ){ echo <<<EOD <td class="itemname">{$k}s</td> <td class="price">{$v}/kg</td> EOD; } ?> The explanation is in the following section. How to use heredocsAs seen in the example, heredocs follow a simple syntax. It starts with <<<EOD and ends with EOD; and the content in between is treated just as if it were in double quotes with the exception that literal double quotes don't have to be escaped making it easier to handle data . Note that although I use the label "EOD", any label can be used as long as it follows PHP guidelines (must contain only alphanumeric characters and underscores and also start with a letter or underscore. The only other guideline you should know is that when you end a heredoc, the label eg. EOD; must be at the start of the line (so if you indent code, please note that it won't work if you have EOD; after whitespace. More examples:
<?php
$menu_html = <<<MENU_DATA <div id="menu"> <strong>Menu</strong> <a href="index.htm">Home Page</a> <a href="articles.htm">Articles</a> <a href="links.htm">Links</a> <a href="forums/" title="Discuss anything in our forums!">Forums</a> </div> MENU_DATA; ?>
<?php $sec_table = 'members' $sql = <<<EOD SELECT a.*, m.name FROM articles AS a JOIN members AS m ON a.author = m.id WHERE a.active = 1 EOD; $articles = mysql_query($sql); ?> |