How can output buffering be used to prevent "headers already sent" errors in PHP scripts?

When PHP scripts send output to the browser before sending headers, it can cause "headers already sent" errors. Output buffering can be used to capture all output before it is sent to the browser, preventing these errors. By enabling output buffering at the beginning of the script, all output is stored in a buffer until it is explicitly flushed, allowing headers to be sent without any issues.

<?php
ob_start(); // Start output buffering

// Your PHP code here

ob_end_flush(); // Flush the output buffer and send it to the browser