How does the use of htmlspecialchars() impact the output of user-generated content in PHP applications?

When user-generated content is displayed on a web page in a PHP application without proper sanitization, it can be vulnerable to Cross-Site Scripting (XSS) attacks. The use of the htmlspecialchars() function in PHP helps mitigate this risk by converting special characters in the user input to their HTML entity equivalents, preventing the browser from interpreting them as code.

// Sanitize user-generated content before displaying it on the web page
$userInput = "<script>alert('XSS attack!')</script>";
$sanitizedInput = htmlspecialchars($userInput);

echo $sanitizedInput;