Search code examples
phpoutput-buffering

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?


Solution

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

    while (ob_get_level()) {
        ob_end_clean();
    }