views:

465

answers:

6

I seem to be confused about PHP output buffering. I have code like this:

function return_json($obj) {
  ob_get_clean();
  ob_start();
  header("Content-Type: application/json");
  echo json_encode($obj);
  exit;
}

But it doesn't seem to like the ob_get_clean(). I do that because some HTML might accidentally get generated before it gets to that point but I thought this was how you were meant to do it.

What am I missing?

+2  A: 

you have to do an ob_start before all your code to catch any output before that function is called

solomongaby
I do ob_start() at the start of my script
Jordie
You need to have it before ob_get_clean()
Johan
+7  A: 

To use ob_get_clean (), you have to be sure, that at some point you have ob_start ()'ed earlier. Otherwise, there’s no buffer to clean, everything is already flushed to the user agent.

Ilya Birman
+1  A: 

If you just want to clean the buffer after starting output buffering with

ob_start()

use

ob_clean()

Also be aware that nothing is already being flushed with functions like echo, print_r, etc. So the first thing in your script should be ob_start(). Be sure your includes do not already send something to the browser.

Sander Versluys
A: 

ob_start needs to be called before any content is generated. Normal usage would be something like:

ob_start();
# generated content here

$content = ob_get_contents(); # $content now contains anything that has been output already
ob_end_clean();

# generate any headers you need
echo $content;
Stoo
+2  A: 

Use the ob_get_level() function to see if an output buffer is active and quit it:

while (ob_get_level()) {
    ob_end_clean();
}
Gumbo
A: 

If the problem you are having is that nothing is going to output, you seem to be missing the flush method? Also, ob_end_clean() can only be called after output buffering has been started, otherwise it returns 'false'. You can't use the ob_ methods to clean up any existing headers that have already been issued, you need to make sure of that yourself.

function return_json($obj) {
  ob_start();
  header("Content-Type: application/json");
  echo json_encode($obj);
  ob_end_flush();
  exit;
}
karim79
This does not seem to be the problem, I tested unknown (yahoo)'s code and PHP flushes on exit just fine. Unfortunately he does not tell us, what his output is.
GrGr