Why is using htmlspecialchars() in the given context not recommended?

Using htmlspecialchars() in this context is not recommended because it will encode all characters, including the ones that are already encoded. This can lead to double encoding and display issues on the webpage. Instead, we should use htmlentities() function with the ENT_QUOTES flag to encode only double quotes, single quotes, ampersands, and less than/greater than signs.

// Fix for not using htmlspecialchars() in this context
$unsafe_input = '<script>alert("XSS Attack!")</script>';
$safe_input = htmlentities($unsafe_input, ENT_QUOTES);
echo $safe_input;