What are the best practices for outputting HTML content using PHP?

When outputting HTML content using PHP, it is important to properly escape any user input to prevent cross-site scripting attacks. One of the best practices is to use the htmlentities() function to encode special characters in the output. This ensures that the HTML content is displayed as intended without any malicious scripts being executed.

<?php
// Example of outputting HTML content using htmlentities()
$user_input = "<script>alert('XSS attack!');</script>";
echo htmlentities($user_input);
?>