?>

Note: This works best on text files. For short strings, stick to mbstring or the library below.

Since automatic detection is never 100% reliable—similar to "decoding an encrypted string without the key"—developers should follow these guidelines: Detect encoding in PHP without multibyte extension?

// Double-check UTF-8 validity if ($detected === 'UTF-8' && !mb_check_encoding($string, 'UTF-8')) return 'Windows-1252'; // common fallback

return 'UTF-8'; // safe fallback

echo $detected; // ISO-8859-1