Jump to content

Output buffering (ob_* functions)


john_

Recommended Posts

I'm a pretty decent coder, I definitely know more than a fair amount of PHP, but one thing I just cant quite grasp is output buffering.

 

What exactly is it? I know for sure that after calling ob_start() you can send data eg (header() then echo a string)

 

 

Link to comment
https://forums.phpfreaks.com/topic/166035-output-buffering-ob_-functions/
Share on other sites

It stored output from your scripts in a buffer, so you can send it when your ready.

 

I know for sure that after calling ob_start() you can send data eg (header() then echo a string)

 

Thats not exactly true. When you call ob_start you are placing your output (headers and all) into a buffer, they are all sent together in one go then when you issue ob_end_flush

 

Theres lots of uses for output buffering, and also lots of reasons why you shouldn't. Using it as a hack to get around header errors is one of the reasons you probably shouldn't.

 

Storing script output for later parsing is one reason why you might use it. A very simple example might be something like a template engine. eg;

 

foo.tpl

<html>
<head>
  <title>{title}</title>
</head>
<body>
  <p>{content}</p>
</body>
</html>

 

parse.php

<?php

$title = 'foo';
$content = 'Here is some content';

ob_start()
include 'foo.tpl';
$template = ob_get_contents();
$template = str_replace('{title}', $title);
$template = str_replace('{content}', $content);
ob_end_clean();
echo $template;

?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.