What are the potential pitfalls of using htmlentities versus htmlspecialchars for encoding special characters in PHP?

The potential pitfall of using htmlentities over htmlspecialchars in PHP is that htmlentities encodes more characters than htmlspecialchars, which could lead to unexpected behavior in certain contexts. To ensure that only the necessary characters are encoded, it is recommended to use htmlspecialchars instead.

// Using htmlspecialchars to encode special characters
$unsafe_input = "<script>alert('XSS attack');</script>";
$safe_input = htmlspecialchars($unsafe_input, ENT_QUOTES, 'UTF-8');
echo $safe_input;