What are the best practices for handling HTML tags and special characters in PHP, particularly when converting them using htmlentities()?

When handling HTML tags and special characters in PHP, it is important to properly sanitize user input to prevent cross-site scripting attacks. One common method is to use the htmlentities() function to convert special characters to their HTML entities, ensuring they are displayed as text rather than being interpreted as code. This helps to secure your application and protect against malicious input.

// Example of using htmlentities() to convert special characters in user input
$user_input = "<script>alert('XSS attack!');</script>";
$sanitized_input = htmlentities($user_input);
echo $sanitized_input;