代码语言:javascript复制
<?php
$str = "中文";
$filename = '1.txt';
file_put_contents($filename,$str);
echo '测试1-检测本地文件编码:' . detect_encoding($filename) . '<br>';
$filename = '2.txt';
file_put_contents($filename,mb_convert_encoding($str,'UTF-8',mb_detect_encoding($str)));
echo '测试2-检测本地文件编码:' . detect_encoding($filename) . '<br>';
$fp =fopen($filename,"w ");
$header ="xefxbbxbf";
fwrite($fp,$header);
fwrite($fp,$str);
fclose($fp);
echo '测试3-检测本地文件编码:' . detect_encoding($filename) . '<br>';
function detect_encoding($file)
{
$list = ['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;
}