What are the advantages of using htmlentities() over htmlspecialchars() in PHP?

When outputting user input on a web page in PHP, it is important to escape special characters to prevent XSS attacks. Both htmlentities() and htmlspecialchars() functions can be used for this purpose, but htmlentities() is preferred over htmlspecialchars() because it encodes more characters, providing better security.

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

// Using htmlentities() to encode special characters
echo htmlentities($user_input);