What are the advantages of using htmlspecialchars when outputting data in PHP?

When outputting data in PHP, it is important to use htmlspecialchars to prevent cross-site scripting (XSS) attacks. This function converts special characters like < and > into their HTML entity equivalents, ensuring that user input is not executed as code. By using htmlspecialchars, you can protect your website from malicious scripts that could potentially steal sensitive information or harm your users.

&lt;?php
$data = &quot;&lt;script&gt;alert(&#039;XSS attack!&#039;)&lt;/script&gt;&quot;;
echo htmlspecialchars($data);
?&gt;