Home > Article > Backend Development > What to do if php parse_ini_string() is garbled?
php parse_ini_string() garbled solution: 1. Enter the file path; 2. Match the encoding method of the file in the provided encoding method array; 3. Pass "iconv($encoding, 'UTF-8 ', $contents);" method to convert it to "UTF-8" encoding.
The operating environment of this tutorial: Windows 7 system, PHP version 8.1, Dell G3 computer.
php parse_ini_string() What should I do if the code is garbled?
Use parse_ini_file to read text documents and encounter Chinese garbled characters
1. Solution to Chinese garbled characters
$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. Read the file content line by line
$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 gets the file content string, parse_ini_string formats the string content
$inistr = file_get_contents($filepath); $ini_items = parse_ini_string($inistr, true);
4. The configuration file config.ini contains Chinese
$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);
Recommended learning: " PHP video tutorial》
The above is the detailed content of What to do if php parse_ini_string() is garbled?. For more information, please follow other related articles on the PHP Chinese website!