How can PHP functions like htmlspecialchars and htmlentities help prevent XSS attacks in web applications?

XSS attacks occur when user input containing malicious scripts is displayed on a website, allowing the scripts to execute in the context of the user's session. PHP functions like htmlspecialchars and htmlentities help prevent XSS attacks by converting special characters in user input to their HTML entity equivalents, rendering them harmless when displayed on the webpage.

// Using htmlspecialchars to prevent XSS attacks
$user_input = "<script>alert('XSS attack!');</script>";
$safe_input = htmlspecialchars($user_input, ENT_QUOTES, 'UTF-8');
echo $safe_input;