How does the encoding of characters impact the output when using htmlentities in PHP?

When using htmlentities in PHP to encode characters, it's important to consider the character encoding of the input and output. If the character encoding is not specified or mismatched, it can lead to unexpected output or rendering issues. To ensure proper encoding, specify the character encoding parameter in the htmlentities function to match the input and output encoding.

// Specify the character encoding parameter to ensure proper encoding
$input = "Hello, <script>alert('XSS attack');</script>";
$output = htmlentities($input, ENT_QUOTES, 'UTF-8');
echo $output;