What are some best practices for securely executing PHP code within HTML templates?

When executing PHP code within HTML templates, it is important to ensure that the code is secure to prevent vulnerabilities such as cross-site scripting (XSS) attacks. One best practice is to always sanitize user input before displaying it on the page to prevent malicious code injection. Another best practice is to avoid using the `eval()` function, as it can execute arbitrary code and pose a security risk.

<?php
// Sanitize user input before displaying it
$userInput = "<script>alert('XSS attack!');</script>";
$sanitizedInput = htmlspecialchars($userInput);

// Display the sanitized input on the page
echo "<p>" . $sanitizedInput . "</p>";
?>