About the detection of file encoding, Baidu A lot of is, but really did not use, many people suggest mb_detect_encoding detection, but I do not know why I this is not successful, nothing output, see someone wrote an enhanced version, with the BOM judgment, I decisively ignored, this thing completely not reliable , and finally, according to the example below the Mb_detect_encoding function in the PHP manual, wrote a detection function,
Also includes the function to automatically detect the encoding and read the file according to the pointing code, the source.
Copy CodeThe code is as follows:
/**
* Detection file encoding
* @param string $file file path
* @return String|null return the encoded 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;
}
/**
* Automatic parsing of encoded read-in Files
* @param string $file file path
* @param string $charset Read encoding
* @return string to return 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 "";
}
http://www.bkjia.com/PHPjc/761018.html www.bkjia.com true http://www.bkjia.com/PHPjc/761018.html techarticle about the file encoding detection, Baidu a lot of is, but really did not use, many people suggest mb_detect_encoding detection, but I do not know why this is not successful, nothing ...