What best practices should be followed when passing values from PHP to HTML code?

When passing values from PHP to HTML code, it is best practice to sanitize and validate the data to prevent security vulnerabilities such as cross-site scripting (XSS) attacks. One way to do this is by using htmlspecialchars() function to encode special characters in the data before outputting it in HTML.

<?php
// Example data to be passed from PHP to HTML
$data = "<script>alert('XSS attack!');</script>";

// Sanitize the data using htmlspecialchars() function
$sanitized_data = htmlspecialchars($data, ENT_QUOTES, 'UTF-8');

// Output the sanitized data in HTML
echo "<p>Data: $sanitized_data</p>";
?>