How can the use of htmlspecialchars() function enhance security in PHP applications?

Using the htmlspecialchars() function in PHP helps enhance security by converting special characters into their HTML entities, preventing potential XSS (Cross-Site Scripting) attacks. This function ensures that user input containing HTML tags or special characters is safely displayed on a webpage without executing any malicious scripts embedded within the input.

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