What are the best practices for including PHP code in HTML files to avoid header errors?

When including PHP code in HTML files, it is important to ensure that no output is sent to the browser before headers are set. To avoid header errors, it is recommended to place all PHP code at the top of the file before any HTML content. Additionally, using functions like ob_start() to buffer output can help prevent header errors.

<?php
ob_start();
// Your PHP code here
?>
<!DOCTYPE html>
<html>
<head>
    <title>Page Title</title>
</head>
<body>
    <!-- Your HTML content here -->
</body>
</html>
<?php
ob_end_flush();
?>