<?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 ="\xef\xbb\xbf";
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;
}

运行结果

UTF-8编码的TXT文件必须以0xef , 0xbb , 0xbf三个字符开头!

Last modification:June 16, 2022
如果觉得我的文章对你有用,请随意赞赏