How can the htmlentities function in PHP be utilized to ensure proper output of text while shortening it?

When outputting text in PHP, it is important to properly escape special characters to prevent cross-site scripting attacks and ensure proper rendering of the text. The htmlentities function can be used to convert special characters to their HTML entities, ensuring that the text is displayed correctly. Additionally, by using htmlentities, the length of the text can be shortened without losing any important information.

$text = "This is a <b>bold</b> text with special characters & symbols";
$shortenedText = substr(htmlentities($text), 0, 20);
echo $shortenedText;