What are the best practices for handling dynamic content within HTML output in PHP?

When handling dynamic content within HTML output in PHP, it is important to properly escape the content to prevent XSS attacks and ensure that the output is secure. One common practice is to use htmlspecialchars() function to encode special characters in the output. Additionally, using prepared statements when interacting with databases can help prevent SQL injection attacks.

<?php
// Example of handling dynamic content within HTML output
$name = "<script>alert('XSS attack!');</script>";
echo "<p>" . htmlspecialchars($name) . "</p>";
?>