How can HTML code with comments and special characters be properly output using PHP?

When outputting HTML code with comments and special characters using PHP, it is important to properly escape the special characters to avoid any syntax errors or rendering issues. This can be achieved by using the htmlspecialchars() function in PHP to convert special characters into their respective HTML entities. Additionally, comments in HTML code can be preserved by wrapping them in PHP echo statements within the HTML output.

<?php
$htmlCode = '<!-- This is a comment --> <p>Special characters: < > &</p>';
echo htmlspecialchars($htmlCode);
?>