What are the differences between htmlentities and htmlspecialchars in terms of preventing HTML code from being displayed in output?

When outputting user-generated content in a web application, it is important to prevent HTML code from being executed to avoid security vulnerabilities like cross-site scripting (XSS) attacks. Both htmlentities and htmlspecialchars are PHP functions that can be used to encode special characters in a string to prevent HTML code from being interpreted by the browser. The main difference between the two is that htmlentities encodes all applicable characters, while htmlspecialchars only encodes characters that have special meaning in HTML.

// Using htmlentities to prevent HTML code from being displayed in output
$user_input = "<script>alert('XSS attack!');</script>";
echo htmlentities($user_input);