Home » Php » buffering – PHP: <<< vs ob_start

buffering – PHP: <<< vs ob_start

Posted by: admin July 12, 2020 Leave a comment

Questions:

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?

How to&Answers:

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).

Answer:

$html = <<<HTML
<p>Hello world</p>
HTML;
// equivalent:
$html = "<p>Hello world</p>";

This uses the PHP string Heredoc syntax, which is a syntax to write a string, similar to using single quotes and double quotes but escape things in a somehow different way. You can use {} to directly insert some PHP strings into it.


<?php
ob_start();
?>
<p>Hello world</p>
<?php
$html = ob_get_clean();

This is a totally different thing. It makes use of the PHP output buffering control to capture things that are not inside PHP code blocks. Like in the given example, <p>Hello world</p> is written outside the PHP code block, which is supposed to be output to the client immediately. With output buffering enabled they are stored inside a buffer in PHP, so that it can be retrieved later using ob_get_contents() or ob_get_clean(). If you need to insert any PHP variables, you need to use <?=$blah?> or even <?php echo $blah?>.


Some CMS use the output buffering control functions to manage contents and modules. One example is Joomla. The advantage of this design is that whenever the module need to place content to its reserved space, it can simply use echo to make the content available. That can simplify the way to obtain contents from the modules, without needing to implement a specific function call or assign to a specific variable, which makes the system easier to manage.

<?php
ob_start();
include dirname(__FILE__)."/content.php";
$content = ob_get_clean();
output_document(array("body"=>$content));

I also make use of output buffering functions such that I can include one file on the top, and without having any PHP at the end I can create a simple template system, but this is sort of off-topic.