Why is it important to use htmlspecialchars when outputting data in PHP to avoid generating broken HTML code?

When outputting data in PHP, it is important to use htmlspecialchars to avoid generating broken HTML code because it helps prevent cross-site scripting (XSS) attacks. By using htmlspecialchars, special characters in the data are converted to their HTML entities, ensuring that the data is displayed as intended without interfering with the HTML structure. This practice helps maintain the integrity and security of the web application by preventing malicious scripts from being injected into the HTML output.

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

// Output the data using htmlspecialchars
echo htmlspecialchars($data, ENT_QUOTES, 'UTF-8');
?>