`
qiujiayu
  • 浏览: 170447 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

PHP 获取文件 或 字符串的编码方式 mb_detect_encoding()

    博客分类:
  • PHP
阅读更多

原理:

使用 mb_detect_encoding() 函数来判断字符串是什么编码的。

注意:要把php.ini中 extension=php_mbstring.dll 前的;号去掉,重启apache就可以了。

我创建三个文件:text1.txt  text2.txt text3.txt

分别以ASCII UTF-8 UNICODE 的编码方式保存

代码如下:

 

 

<?php
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($text) {
    $first2 = substr($text, 0, 2);
    $first3 = substr($text, 0, 3);
    $first4 = substr($text, 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';
}
function getFileEncoding($str){
    $encoding=mb_detect_encoding($str);
    if(empty($encoding)){
        $encoding=detect_utf_encoding($str);
    }
    return $encoding;
}
$file = 'text1.txt';
echo getFileEncoding(file_get_contents($file));  // 输出ASCII
echo '<br />';

$file = 'text2.txt';
echo getFileEncoding(file_get_contents($file));  // 输出UTF-8
echo '<br />';
$file = 'text3.txt';
echo getFileEncoding(file_get_contents($file));  // 输出UTF-16LE
echo '<br />';
?>

分享到:
评论
1 楼 rzl888 2010-06-24  
不错 学习了

相关推荐

Global site tag (gtag.js) - Google Analytics