Home  >  Article  >  Backend Development  >  Example of how to detect file encoding in php_PHP tutorial

Example of how to detect file encoding in php_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 10:31:48676browse

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.

Copy code The code is as follows:

/**
* Detect file encoding
* @param string $file file path
* @return string|null return 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)) {
                                                                                       
/**
* Automatically parse the encoding and read the file
* @param string $file File path
* @param string $charset Read the encoding* @return string Return 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 "";
}





http://www.bkjia.com/PHPjc/761018.htmlwww.bkjia.com

truehttp: //www.bkjia.com/PHPjc/761018.htmlTechArticle Regarding the detection of file encoding, Baidu has a lot of them, but there is really nothing that can be used, and many people have suggested it. mb_detect_encoding detection, but for some reason I failed, nothing...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn