How can the htmlentities() function be effectively used to prevent XSS attacks while still allowing for the inclusion of HTML and CSS formatting in PHP-generated content?

To prevent XSS attacks while still allowing HTML and CSS formatting in PHP-generated content, the htmlentities() function can be used to encode special characters in the output. This function converts characters like <, >, ", ', and & into their respective HTML entities, which will prevent them from being interpreted as code by the browser. By using htmlentities() on user-generated content before displaying it on the webpage, you can ensure that any potential malicious scripts are neutralized.

// Example of using htmlentities() to prevent XSS attacks while allowing HTML and CSS formatting
$user_input = &quot;&lt;script&gt;alert(&#039;XSS attack!&#039;)&lt;/script&gt;&quot;;
$safe_output = htmlentities($user_input);
echo &quot;&lt;div style=&#039;color: red;&#039;&gt;$safe_output&lt;/div&gt;&quot;;