What best practices should be followed when outputting data to HTML in PHP to prevent XSS vulnerabilities?

To prevent XSS vulnerabilities when outputting data to HTML in PHP, it is important to properly sanitize and escape the data before rendering it on the page. This can be done using functions like htmlspecialchars() or htmlentities() to encode special characters in the data.

<?php
// Sample data to be outputted
$data = "<script>alert('XSS attack');</script>";

// Sanitize and escape the data before outputting
echo htmlspecialchars($data, ENT_QUOTES, 'UTF-8');
?>