Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a better way to write HTML strings in PHP?

Tags:

I find myself writing a lot of functions in PHP that return HTML code. They may look something like this:

function html_site_head() {     return         "             <div id=\"site_header\">                 <div id=\"site_header_inner\">                     <div id=\"site_header_logo\"></div>                      <div id=\"site_header_countdown\">BARE XX DAGER IGJEN</div>                 </div>             </div>         "; } 

Now I can swear I've seen better ways to write long strings in PHP. I like python's way of doing it:

return """     <div id="site_header">         <div id="site_header_inner">             <div id="site_header_logo"></div>              <div id="site_header_countdown">BARE XX DAGER IGJEN</div>         </div>     </div> """ 

As you don't have to escape quotation marks. An alternative is using single quotation marks, but that means no using PHP variables directly in the string. I swear I've seen something like this in PHP:

return <<<     <div id="site_header">         <div id="site_header_inner">             <div id="site_header_logo"></div>              <div id="site_header_countdown">BARE XX DAGER IGJEN</div>         </div>     </div> 

Or something similar. Could someone refresh my memory on this?

Thanks

like image 348
Hubro Avatar asked Dec 22 '10 14:12

Hubro


1 Answers

PHP knows several kinds of syntax to declare a string:

  • single quoted

    ' … ' 
  • double quoted

    " … " 
  • heredoc syntax

    <<<DELIMITER  … DELIMITER 
  • nowdoc syntax (since PHP 5.3.0)

    <<<'DELIMITER'  … DELIMITER 

So you don’t have to use the double quotes per se.

like image 139
Gumbo Avatar answered Nov 19 '22 20:11

Gumbo