In PHP, what considerations should be taken into account when displaying user-generated content with HTML markup in previews or views?

When displaying user-generated content with HTML markup in previews or views, it is important to properly sanitize and escape the content to prevent Cross-Site Scripting (XSS) attacks. This can be achieved by using PHP's htmlspecialchars() function to encode special characters in the user input before displaying it on the page.

<?php
$userInput = "<script>alert('XSS attack!');</script>";
echo htmlspecialchars($userInput, ENT_QUOTES, 'UTF-8');
?>