What potential issues can arise when using htmlentities in PHP to encode special characters and how can they be resolved?

When using htmlentities in PHP to encode special characters, one potential issue that can arise is double encoding, where characters are encoded multiple times, leading to incorrect display of the content. This can be resolved by first checking if the string is already encoded using htmlentities before encoding it again.

// Check if the string is already encoded before using htmlentities
if (!mb_detect_encoding($string, 'UTF-8', true)) {
    $encodedString = htmlentities($string, ENT_QUOTES, 'UTF-8');
} else {
    $encodedString = $string;
}

// Output the encoded string
echo $encodedString;