What are the best practices for handling HTML output within PHP code to ensure proper functionality?

When outputting HTML within PHP code, it is important to properly escape any user input to prevent cross-site scripting (XSS) attacks. One way to do this is by using the htmlspecialchars() function to encode special characters. Additionally, separating HTML markup from PHP logic by using a templating system or alternative syntax like PHP short tags can help maintain code readability and organization.

<?php
// Example of properly escaping HTML output in PHP
$user_input = '<script>alert("XSS attack")</script>';
echo htmlspecialchars($user_input, ENT_QUOTES, 'UTF-8');
?>