Php file encoding method. For file encoding detection, Baidu has always regarded it as "all", but it does not work. many people suggest mb_detect_encoding Detection. but somehow I am not successful, and I have nothing to do with file encoding detection, baidu uses Baidu refer, but it does not work. many people suggest mb_detect_encoding detection, but I don't know why I didn't succeed. I didn't output anything. I saw someone wrote an enhanced version and used BOM to judge it, I ignored it decisively. it was totally unreliable. Finally, according to the example below the mb_detect_encoding function in the PHP manual, I wrote a detection function myself,
It also includes functions and source code that automatically detect the encoding and read the file according to the instruction code.
The code is as follows:
/**
* Check the file encoding.
* @ Param string $ file path
* @ Return string | null returns the encoding name or null.
*/
Function detect_encoding ($ file ){
$ 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 $ item;
}
}
Return null;
}
/**
* Automatically parse the encoding to read the file
* @ Param string $ file path
* @ Param string $ charset read encoding
* @ Return string returns the read content
*/
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 "";
}
Mb_detect_encoding detection, but I don't know why I didn't succeed. nothing...