Home >Backend Development >PHP Tutorial >Example of how to detect file encoding in php_PHP tutorial
Regarding the detection of file encoding, there are a lot of them on Baidu, but there is really no usable one. Many people suggested mb_detect_encoding detection, but for some reason it failed for me and nothing was output. I saw someone wrote an enhancement. version, using BOM to judge, I ignored it decisively. This thing is completely unreliable. Finally, I wrote a detection function based on the example below the mb_detect_encoding function in the PHP manual.
It also includes automatic detection of encoding and encoding according to the instructions. The function and source code for reading files are presented.
*/
function auto_read($file, $charset='UTF-8') {
$list = array('GBK', 'UTF-8', 'UTF -16LE', 'UTF-16BE', 'ISO-8859-1');
$str = file_get_contents($file);
foreach ($list as $item) {
$tmp = mb_convert_encoding ($str, $item, $item);
if (md5($tmp) == md5($str)) {
return mb_convert_encoding($str, $charset, $item);
}
}
return "";
}