What are the best practices for handling and outputting HTML code in PHP?

When handling and outputting HTML code in PHP, it is important to properly escape the HTML entities to prevent cross-site scripting attacks and maintain the integrity of the HTML structure. One common method to achieve this is by using the htmlspecialchars() function in PHP, which converts special characters to their HTML entities.

// Example of handling and outputting HTML code in PHP
$html_code = "<h1>Hello, World!</h1>";
echo htmlspecialchars($html_code);