What are the best practices for handling HTML content input from users in PHP applications?

When handling HTML content input from users in PHP applications, it is important to sanitize and validate the input to prevent potential security vulnerabilities such as Cross-Site Scripting (XSS) attacks. One way to achieve this is by using PHP's built-in functions like htmlspecialchars() to escape special characters and prevent them from being interpreted as HTML code.

// Sanitize HTML content input from users
$userInput = "<script>alert('XSS attack!');</script>";
$sanitizedInput = htmlspecialchars($userInput, ENT_QUOTES, 'UTF-8');

echo $sanitizedInput;