How can output buffering be utilized to prevent "headers already sent" errors when generating CSV files in PHP?

When generating CSV files in PHP, "headers already sent" errors can occur if any content is output before the headers are set. To prevent this, output buffering can be utilized to capture the output before sending it to the browser, allowing headers to be set without interference. This ensures that the CSV file is generated correctly without any errors.

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

// Set headers for CSV file
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="example.csv"');

// Generate CSV content
$csvData = "Name, Age, Email\nJohn Doe, 30, john@example.com";

// Output CSV content
echo $csvData;

// Flush output buffer
ob_end_flush(); // Send output and turn off output buffering