Is it necessary to use htmlentities() when outputting text in PHP, and how does it affect the readability of the content?

When outputting text in PHP, it is important to use htmlentities() to prevent cross-site scripting attacks by converting characters that have special meaning in HTML to their respective HTML entities. This function helps to sanitize user input and ensure that the content is displayed as intended without any unintended code execution. While htmlentities() may affect the readability of the content by converting special characters to their HTML entities, it is a necessary security measure to protect against malicious attacks.

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