php parse_ini_string()乱码的解决办法:1、输入文件路径;2、在提供的编码方式数组中,匹配文件的编码方式;3、通过“iconv($encoding, 'UTF-8', $contents);”方式转为“UTF-8”编码即可。

本教程操作环境:windows7系统、PHP8.1版、Dell G3电脑。

php parse_ini_string() 乱码怎么办?

使用parse_ini_file读取文本文档遇到中文乱码问题

1、中文乱码解决方法

$contents = file_get_contents("config.ini");
//输入文件路径
$encoding = mb_detect_encoding($contents, array('UTF-16', 'UTF-8', 'GBK','ASCII', 'SJIS', 'BIG-5'), true);
//在提供的编码方式数组中,匹配文件的编码方式
$rst = iconv($encoding, 'UTF-8', $contents);//转为"UTF-8"编码

2、逐行读取文件内容

      $contents = file_get_contents($rstPath);//$rstPath-目标文件路径
        $encoding = mb_detect_encoding($contents, array('UTF-16', 'UTF-8', 'GBK','ASCII', 'SJIS', 'BIG-5'), true);
 
        $file_handle = fopen($rstPath, "r");
        while (!feof($file_handle)) 
        {
            $line = fgets($file_handle);
            if(empty($line)) continue;//当前行内容为空,进入下一循环
            $line = iconv($encoding, 'UTF-8', $line);
 
            //...业务逻辑
        }
        fclose($file_handle);

3、file_get_contents获取文件内容字符串,parse_ini_string格式化字符串内容

$inistr = file_get_contents($filepath);
$ini_items = parse_ini_string($inistr, true);

4、配置文件config.ini中含有中文

$iniPath = FCPATH . 'config.ini';
$iniContent = file_get_contents($iniPath);//读取配置文件
$encoding = mb_detect_encoding($iniContent, array('UTF-16', 'UTF-8', 'GBK', 'ASCII', 'SJIS', 'BIG-5'), true);//匹配编码方式
$iniContent = iconv($encoding, 'UTF-8', $iniContent);//转换编码方式
$iniContent = parse_ini_string($iniContent, true, INI_SCANNER_RAW);


php parse_ini_string() 乱码怎么办