🐘 PHP Intermediate

What is output buffering in PHP?

Why Interviewers Ask This

Candidates at the intermediate level are expected to not only know this concept but explain the trade-offs involved. Interviewers use this question to see if you can reason about design decisions, not just recall facts.

Answer

Output buffering tells PHP to store all output (HTML, echo statements) in a buffer rather than sending it directly to the browser. Start buffering with ob_start(), retrieve the buffer as a string with ob_get_clean() or ob_get_contents(), and send/discard with ob_end_flush() or ob_end_clean(). Key use cases: modifying output before sending (adding headers, compressing), capturing the output of functions that echo instead of return, using header() or setcookie() after some output has been generated (normally these require being before any output), and template systems that capture rendered HTML. Many PHP frameworks use output buffering internally for response handling.

Pro Tip

This topic has PHP-specific nuances that differ from general programming. Highlighting those nuances in your answer shows expertise rather than generic knowledge.