4

I have this code:

<?php
ob_start();
?>
hi
<?php echo ob_get_contents(); ob_end_clean();

But nothing is outputted.
If I remove the ob_end_clean(); the output is hi hi. If ob_flush() isn't called at the end of the app, the contents are automatically flushed, again.

I need to use ob_get_contents() because I am going to implement a simple caching mechanism that saves the the output to a file.

Please help.

Thanks!

  • 5
    Yeah you're echoing the output buffer to the output buffer. It needs to be assigned to a variable and echoed after `ob_end_clean();` – rfoo Apr 19 '14 at 01:39

1 Answers1

7

Update: I am surprised but your example does actually work with output buffering. I did not think that HTML between php tags would work but it does.

<?php
ob_start();
?>
Hello World
<?php 
echo "Goodbye";
$test = ob_get_contents(); ob_end_clean(); echo "output:".$test;
?>

This outputs output: Hello World Goodbye.

The problem is you are echoing ob_get_contents into the buffer. As your question in the comments was about templating, I still think you are going about output buffering wrong. You should push PHP variables into an HTML template, not pull an HTML template into a PHP script. You should also look into a controller/view solution but below is a basic example.

Templating: For templating, a basic example could be:

<?php
ob_start();
...PHP LOGIC HERE...
...PHP LOGIC HERE...
...PHP LOGIC HERE...
$content = ob_get_contents();
ob_end_clean();
?>
<html>
<body>
<div><?php echo $content; ?></div>
</body></html>
Devon Bessemer
  • 34,461
  • 9
  • 69
  • 95
  • no, it doesn't work. having ` hi ` works as intended, so I don't think that's the case –  Apr 19 '14 at 01:21
  • @jasonszhao You are trying to capture elements in the buffer _before_ outputting. Closing PHP and putting `hi` ends the buffer before it captures it. – WASasquatch Apr 19 '14 at 01:26
  • @Devon It is not buffering for me. Only if I contain the HTML outside the PHP tags with `if` `else` conditioning, are you sure? Without it it seems to just close PHP. I am running PHP 5.3 – WASasquatch Apr 19 '14 at 03:12
  • When I do it outside the buffer I get a read time of `0.0000140000` to `0.0000180000` when I do it per the documentation and in variables I get `0.0000120000` to `0.0000150000` average in timing. i'd like to know what the differences are. – WASasquatch Apr 19 '14 at 03:25
  • 1
    @WASasquatch the code I put at the top worked for me. – Devon Bessemer Apr 19 '14 at 04:03