What potential pitfalls should be considered when combining HTML and PHP code within an echo statement in PHP?

When combining HTML and PHP code within an echo statement in PHP, it is important to ensure that the code is properly escaped to prevent any syntax errors or vulnerabilities such as cross-site scripting (XSS) attacks. One way to avoid these pitfalls is to use PHP's htmlentities() function to encode any HTML special characters in the output.

<?php
// Example of combining HTML and PHP code within an echo statement with proper escaping
$name = "<script>alert('XSS attack!')</script>"; // Example input containing HTML and JavaScript code

echo "Hello, " . htmlentities($name) . "!"; // Output the sanitized input
?>