What are the potential security risks associated with dynamically generating HTML code using PHP and how can they be mitigated?

One potential security risk of dynamically generating HTML code using PHP is Cross-Site Scripting (XSS) attacks, where malicious scripts are injected into the generated HTML. To mitigate this risk, you can use the htmlspecialchars function in PHP to encode special characters in the output HTML, preventing the execution of any injected scripts.

<?php
// Dynamically generate HTML code
$unsafe_data = $_GET['data']; // This data could be user input or from an external source
$safe_data = htmlspecialchars($unsafe_data, ENT_QUOTES, 'UTF-8');

// Output the safe data in the HTML
echo "<div>$safe_data</div>";
?>