What are the implications of using htmlentities() in PHP for security, and when should it be used in code?

Using htmlentities() in PHP is important for security as it helps prevent Cross-Site Scripting (XSS) attacks by converting special characters into their HTML entities. It should be used whenever user input is being displayed on a webpage to ensure that any potentially malicious scripts are not executed.

$user_input = "<script>alert('XSS attack!');</script>";
echo htmlentities($user_input);