What are the best practices for incorporating variables into PHP code for generating HTML content?

When incorporating variables into PHP code for generating HTML content, it is important to properly sanitize and validate the input to prevent security vulnerabilities such as cross-site scripting attacks. One best practice is to use htmlspecialchars() function to escape special characters in the variable values before outputting them in HTML.

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

// Sanitize the variable before outputting in HTML
echo htmlspecialchars($name);
?>