How can the htmlspecialchars() function be utilized to prevent security vulnerabilities in PHP-generated HTML code?

The htmlspecialchars() function in PHP can be utilized to prevent security vulnerabilities such as cross-site scripting (XSS) attacks by converting special characters like < and > into their HTML entities. This ensures that user input is displayed as text on the webpage rather than being interpreted as HTML code, thus preventing malicious scripts from being executed.

$user_input = &quot;&lt;script&gt;alert(&#039;XSS attack!&#039;);&lt;/script&gt;&quot;;
$safe_input = htmlspecialchars($user_input);
echo $safe_input;