What role does htmlspecialchars play in preventing XSS attacks when outputting user-generated content in PHP?

When outputting user-generated content in PHP, it is crucial to sanitize the input to prevent cross-site scripting (XSS) attacks. One way to do this is by using the htmlspecialchars function, which converts special characters to HTML entities, rendering them harmless and preventing malicious scripts from being executed.

// Sanitize and output user-generated content using htmlspecialchars
$userContent = "<script>alert('XSS attack!');</script>";
echo htmlspecialchars($userContent, ENT_QUOTES, 'UTF-8');