In PHP, what is the significance of using htmlspecialchars() when outputting database results in HTML?

When outputting database results in HTML, using htmlspecialchars() is important 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 interpreted as HTML code. By using htmlspecialchars(), you can securely display data from the database without risking the execution of malicious scripts.

&lt;?php
// Fetch data from the database
$result = &quot;&lt;script&gt;alert(&#039;XSS attack!&#039;);&lt;/script&gt;&quot;;

// Output the data using htmlspecialchars()
echo htmlspecialchars($result);
?&gt;