What are best practices for handling character encoding and output in PHP to avoid header modification errors?

When handling character encoding and output in PHP, it is important to set the correct charset in both the PHP code and the HTML output to avoid header modification errors. To ensure proper encoding, use functions like `header()` to set the content type and charset, and `mb_internal_encoding()` to set the internal character encoding. Additionally, sanitize user input and escape output to prevent any potential security vulnerabilities.

<?php
// Set the content type and charset
header('Content-Type: text/html; charset=UTF-8');
// Set the internal character encoding
mb_internal_encoding('UTF-8');

// Sanitize user input
$user_input = filter_input(INPUT_POST, 'user_input', FILTER_SANITIZE_STRING);

// Output escaped content
echo htmlspecialchars($user_input, ENT_QUOTES, 'UTF-8');
?>