What are best practices for handling PHP variables within HTML output to avoid errors?

When outputting PHP variables within HTML, it is best practice to properly escape the variables to prevent errors or vulnerabilities such as cross-site scripting (XSS) attacks. One way to achieve this is by using the htmlspecialchars() function in PHP to encode special characters in the variable before outputting it in HTML.

<?php
// Example PHP variable
$name = "<script>alert('XSS attack');</script>";

// Output the variable safely within HTML using htmlspecialchars()
echo "<p>Hello, " . htmlspecialchars($name) . "</p>";
?>