What best practices should be followed when inserting values into HTML code in PHP?

When inserting values into HTML code in PHP, it is important to properly sanitize and escape the data to prevent cross-site scripting (XSS) attacks. One common method to achieve this is by using the htmlspecialchars() function to encode special characters in the input data before outputting it to the HTML document.

<?php
// Example input data
$input_data = "<script>alert('XSS attack!');</script>";

// Sanitize and escape the input data
$sanitized_data = htmlspecialchars($input_data, ENT_QUOTES, 'UTF-8');

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