Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Output buffering in PHP?

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?

like image 643
Jordie Avatar asked Aug 21 '26 04:08

Jordie


1 Answers

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.

like image 189
Ilya Birman Avatar answered Aug 22 '26 22:08

Ilya Birman