PHP有没有判断一个文件或者一段字符串是什么编码的函数?

2024-12-16 13:24:04
推荐回答(2个)
回答1:

测试:将 text1.txt 保存成 ASCII编码, text2.txt 保存成 UTF-8 编码

function chkCode($string){
$code = array('ASCII', 'GBK', 'UTF-8');
foreach($code as $c){
if( $string === iconv('UTF-8', $c, iconv($c, 'UTF-8', $string))){
return $c;
}
}
return null;
}

$file = 'text1.txt';
echo chkCode(file_get_contents($file)); // 输出ASCII
echo '
';

$file = 'text2.txt';
echo chkCode(file_get_contents($file)); // 输出UTF-8
echo '
';
?>

回答2:

测试:将
text1.txt
保存成
ASCII编码,
text2.txt
保存成
UTF-8
编码
function
chkCode($string){
$code
=
array('ASCII',
'GBK',
'UTF-8');
foreach($code
as
$c){
if(
$string
===
iconv('UTF-8',
$c,
iconv($c,
'UTF-8',
$string))){
return
$c;
}
}
return
null;
}
$file
=
'text1.txt';
echo
chkCode(file_get_contents($file));
//
输出ASCII
echo
'/>';
$file
=
'text2.txt';
echo
chkCode(file_get_contents($file));
//
输出UTF-8
echo
'/>';
?>