How can the htmlspecialchars function be used to prevent security vulnerabilities in PHP code?

Using the htmlspecialchars function in PHP helps prevent security vulnerabilities such as cross-site scripting (XSS) attacks by converting special characters to their HTML entities. This ensures that user input is displayed as text on the page rather than being interpreted as HTML code, reducing the risk of malicious scripts being executed.

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