In PHP sometimes I see this:
$html = <<<HTML
<p>Hello world</p>
HTML;
Normally I would have used ob_start() :
ob_start();
?>
<p>Hello world</p>
<?php
$html = ob_get_contents();
ob_clean();
Can you tell me what the difference between these two ways to write to the buffer and their advantages?
HEREDOC (<<<
) is just another way to write a string data into a variable. The output buffer, on the other hand, will catch all output that takes place after ob_start()
including (HTML) output of any warnings or errors you might have in the code before you call ob_get_contents()
;
Usually, if you just need to format a string with HTML, just use HEREDOC or regular string notation. Output buffer is usually used if you need to catch output before you send any HTTP headers (for an example, if you're using FirePHP to debug your application, you'll need to use output buffering because FirePHP embeds the logging data in the HTTP headers).