How can htmlspecialchars be used to ensure data security when outputting values in PHP?

When outputting values in PHP, it is important to sanitize the data to prevent cross-site scripting attacks. One way to do this is by using the htmlspecialchars function, which converts special characters to HTML entities. This ensures that any potentially malicious code is displayed as plain text rather than being executed.

<?php
// Outputting a variable with htmlspecialchars to prevent XSS attacks
$unsafe_data = "<script>alert('XSS attack!');</script>";
$safe_data = htmlspecialchars($unsafe_data);
echo $safe_data;
?>