Why is it important to specify the charset parameter when using htmlspecialchars() in PHP?

When using the htmlspecialchars() function in PHP, it is important to specify the charset parameter to ensure that the function properly encodes special characters based on the specified character set. If the charset parameter is not specified, the function may not encode certain characters correctly, leading to potential security vulnerabilities such as cross-site scripting attacks.

$text = "<script>alert('Hello, world!');</script>";
$encoded_text = htmlspecialchars($text, ENT_QUOTES, 'UTF-8');
echo $encoded_text;