What security considerations should be taken into account, such as preventing XSS vulnerabilities, when dynamically generating HTML content with PHP?

When dynamically generating HTML content with PHP, it is important to prevent XSS vulnerabilities by properly escaping user input. This can be done by using functions like htmlspecialchars() to encode special characters in the output. Additionally, it is recommended to validate and sanitize user input before outputting it to the HTML.

$userInput = $_POST['user_input'];
$escapedInput = htmlspecialchars($userInput, ENT_QUOTES, 'UTF-8');
echo "<div>$escapedInput</div>";