What are some best practices for echoing HTML code in PHP?

When echoing HTML code in PHP, it is important to properly escape any variables to prevent cross-site scripting attacks. One common way to do this is by using the htmlspecialchars() function to encode special characters. Additionally, it is recommended to separate PHP logic from HTML presentation by using a templating system or alternative syntax like PHP short tags.

<?php
// Example of echoing HTML code in PHP with proper escaping
$name = "<script>alert('XSS attack!');</script>";
echo "<p>Hello, " . htmlspecialchars($name) . "</p>";
?>