What are the best practices for handling HTML code within PHP echo statements to avoid parsing errors?

When handling HTML code within PHP echo statements, it's important to properly escape characters that may cause parsing errors. One common practice is to use the PHP function htmlspecialchars() to convert special characters to HTML entities. This ensures that the HTML code is displayed correctly without interfering with the PHP parsing.

<?php
$html_code = "<h1>Hello, World!</h1>";
echo htmlspecialchars($html_code);
?>