Why is htmlentities() suggested as a solution in this context?

The issue is that user input is being displayed directly on a webpage without any sanitization, which can lead to Cross-Site Scripting (XSS) attacks. To solve this, we need to sanitize the user input by using htmlentities() function in PHP. This function converts special characters to HTML entities, preventing them from being interpreted as HTML or JavaScript code.

// Sanitize user input using htmlentities()
$user_input = "<script>alert('XSS attack');</script>";
$sanitized_input = htmlentities($user_input);

echo $sanitized_input;