How can htmlentities() function be used to safely output HTML tags in PHP?

When outputting user-generated content in PHP, it's important to sanitize the data to prevent cross-site scripting (XSS) attacks. One way to safely output HTML tags is by using the htmlentities() function in PHP. This function converts special characters to their HTML entities, rendering them harmless and preventing any malicious code from being executed.

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