What are best practices for handling character encoding and escaping in PHP to prevent issues with special characters in HTML output?

Special characters in HTML output can cause issues if not properly encoded or escaped. To prevent problems, it is essential to use functions like htmlspecialchars() to encode special characters and prevent XSS attacks. Additionally, setting the correct character encoding in both the HTML document and PHP script will ensure that special characters are displayed correctly.

// Set the character encoding
header('Content-Type: text/html; charset=UTF-8');

// Encode special characters in output
echo htmlspecialchars($output);