What are some best practices for handling HTML output in PHP to prevent displaying unwanted content?

When outputting HTML in PHP, it is essential to properly sanitize the data to prevent Cross-Site Scripting (XSS) attacks. One common method to sanitize HTML output is by using the htmlspecialchars() function to convert special characters into HTML entities. This ensures that any user input is displayed as plain text and not interpreted as HTML code.

// Sample PHP code snippet to sanitize HTML output using htmlspecialchars()

// Unsafe user input
$userInput = "<script>alert('XSS attack!');</script>";

// Sanitize the user input
$sanitizedInput = htmlspecialchars($userInput, ENT_QUOTES, 'UTF-8');

// Output the sanitized input
echo $sanitizedInput;