What role does the htmlspecialchars() function play in preventing issues with special characters in PHP?

Special characters in user input can potentially be used for Cross-Site Scripting (XSS) attacks if not properly sanitized. The htmlspecialchars() function in PHP converts special characters to their corresponding HTML entities, preventing them from being interpreted as code and thus mitigating the risk of XSS attacks.

$user_input = "<script>alert('XSS attack');</script>";
$sanitized_input = htmlspecialchars($user_input, ENT_QUOTES, 'UTF-8');
echo $sanitized_input;