How can the use of htmlspecialchars() function be beneficial when generating HTML output in PHP?

When generating HTML output in PHP, it is important to sanitize user input to prevent cross-site scripting (XSS) attacks. The htmlspecialchars() function converts special characters like < and > into their HTML entities, preventing them from being interpreted as code by the browser. This helps to ensure that user input is displayed as plain text and not executed as code.

// Example of using htmlspecialchars() to sanitize user input
$user_input = &quot;&lt;script&gt;alert(&#039;XSS attack!&#039;)&lt;/script&gt;&quot;;
$sanitized_input = htmlspecialchars($user_input);
echo $sanitized_input;