// Unicode BOM is U+FEFF, but after encoded, it will look like this.
define ('UTF32_BIG_ENDIAN_BOM' , chr(0x00) . chr(0x00) . chr(0xFE) . chr(0xFF));
define ('UTF32_LITTLE_ENDIAN_BOM', chr(0xFF) . chr(0xFE) . chr(0x00) . chr(0x00));
define ('UTF16_BIG_ENDIAN_BOM' , chr(0xFE) . chr(0xFF));
define ('UTF16_LITTLE_ENDIAN_BOM', chr(0xFF) . chr(0xFE));
define ('UTF8_BOM' , chr(0xEF) . chr(0xBB) . chr(0xBF));
function detect_utf_encoding($content)
{
$first2 = substr($content, 0, 2);
$first3 = substr($content, 0, 3);
$first4 = substr($content, 0, 3);
if ($first3 == UTF8_BOM) return 'UTF-8';
elseif ($first4 == UTF32_BIG_ENDIAN_BOM) return 'UTF-32BE';
elseif ($first4 == UTF32_LITTLE_ENDIAN_BOM) return 'UTF-32LE';
elseif ($first2 == UTF16_BIG_ENDIAN_BOM) return 'UTF-16BE';
elseif ($first2 == UTF16_LITTLE_ENDIAN_BOM) return 'UTF-16LE';
else return false;
}
function detect_file_encoding($file)
{
$contents = file_get_contents($file);
if(($encoding = detect_utf_encoding($contents)) != false)
return $encoding;
if(preg_match("/^[\\x00-\\xFF]*$/u", $contents) === 0)
return "ISO-8859-1";
return mb_detect_encoding(file_get_contents($file), "auto");
}
echo detect_file_encoding(__FILE__);