Why is it important to gather all necessary information, including page titles, before sending headers to the browser in PHP?

It is important to gather all necessary information, including page titles, before sending headers to the browser in PHP because once headers are sent, it is not possible to modify them. This can lead to errors or unexpected behavior if headers are sent before setting necessary information like page titles. By gathering all necessary information first, we can ensure that headers are sent with the correct information and avoid any issues.

<?php
// Gather all necessary information, including page titles
$pageTitle = "My Page Title";

// Send headers to the browser after gathering all necessary information
header("Content-Type: text/html");
echo "<!DOCTYPE html>";
echo "<html>";
echo "<head><title>$pageTitle</title></head>";
echo "<body>";
// Rest of the HTML content
echo "</body>";
echo "</html>";
?>