What is the importance of using htmlspecialchars() for variables values when outputting them in HTML in PHP?

When outputting variable values in HTML in PHP, it is important to use the htmlspecialchars() function to prevent cross-site scripting (XSS) attacks. This function converts special characters like <, >, and & into their HTML entities, ensuring that they are displayed as text and not interpreted as HTML code by the browser. By using htmlspecialchars(), you can protect your website from malicious scripts that could potentially harm users or steal sensitive information.

&lt;?php
// Variable containing user input
$userInput = &quot;&lt;script&gt;alert(&#039;XSS attack!&#039;)&lt;/script&gt;&quot;;

// Output the user input safely using htmlspecialchars()
echo htmlspecialchars($userInput);
?&gt;