What are the common pitfalls of writing HTML code for PHP scripts and how can they be avoided?

One common pitfall is not properly escaping PHP variables when outputting them in HTML code, which can lead to security vulnerabilities like cross-site scripting attacks. To avoid this, always use htmlentities() or htmlspecialchars() functions to escape the variables before displaying them in HTML.

<?php
$name = "<script>alert('XSS attack!');</script>";
echo htmlentities($name);
?>