How can one avoid the "Cannot modify header information" error in PHP when trying to redirect?

When trying to redirect in PHP, the "Cannot modify header information" error may occur if there is any output sent to the browser before the header() function is called. To avoid this error, make sure to call the header() function before any output is sent to the browser, such as HTML, whitespace, or error messages.

<?php
ob_start();
header('Location: https://www.example.com');
exit();
ob_end_flush();
?>