How can the htmlspecialchars() function be effectively integrated into PHP code to prevent XSS vulnerabilities?

To prevent XSS vulnerabilities in PHP, the htmlspecialchars() function can be used to convert special characters to HTML entities. This function ensures that user input is displayed as text on the webpage, rather than being interpreted as HTML or JavaScript code. By using htmlspecialchars() on any user-generated content before displaying it on a webpage, you can effectively mitigate the risk of XSS attacks.

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