How can the use of htmlspecialchars instead of htmlentities improve the handling of character encoding in PHP?

When handling character encoding in PHP, using htmlspecialchars instead of htmlentities can improve security by encoding special characters in HTML entities, preventing potential XSS attacks. htmlspecialchars is specifically designed to encode characters in HTML, while htmlentities encodes characters for various contexts, potentially leading to unintended behavior. By using htmlspecialchars, you ensure that all special characters are properly encoded for HTML output.

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