What are the best practices for handling headers and output in PHP scripts to avoid errors like "headers already sent"?

When working with headers in PHP scripts, it is important to ensure that no output is sent to the browser before setting headers. To avoid errors like "headers already sent", it is recommended to place all header functions at the beginning of the script before any output is generated.

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

// Set headers before any output
header("Content-Type: text/html");

// Your PHP code here

ob_end_flush(); // Flush output buffer
?>