What are the common pitfalls to avoid when using PHP echo statements with HTML attributes and variables?

When using PHP echo statements with HTML attributes and variables, common pitfalls to avoid include not properly escaping the variables to prevent XSS attacks and ensuring that the HTML attributes are correctly quoted. To solve this issue, always use htmlspecialchars() to escape variables and make sure to properly quote HTML attributes.

<?php
// Example of using htmlspecialchars() and properly quoting HTML attributes
$name = "<script>alert('XSS attack!')</script>";
echo "<input type='text' name='" . htmlspecialchars($name, ENT_QUOTES) . "'>";
?>