php fgetcsv is garbled because the imported csv file is saved in ansi encoding. The solution is to set the encoding corresponding to the Chinese operating system environment to "gbk", that is, to manually change the browser character encoding to "gbk" will do.
Recommended: "PHP Tutorial"
Solution to the problem of garbled characters when reading csv files using fgetcsv in php Method
Generally speaking, encountering garbled characters in PHP is mostly due to encoding problems. Here we analyze the causes and solutions of garbled characters when fgetcsv reads csv files.
The example is as follows:
The code is as follows:
function get_csv_contents( $file_target ){ $handle = fopen( $file_target, 'r'); while ($data = fgetcsv($handle, 1000, ",")) { $num = count($data); echo "<p> $num fields in line $row: <br>n"; $row++; for ($c=0; $c < $num; $c++) { echo $data[$c]. "<br>n";; /*echo getUTFString($data[$c])*/ } } fclose($handle); }
The imported csv file is saved in ansi encoding. For the Chinese operating system environment, the corresponding one should be gbk encoding. Pass Manually changed the browser character encoding to gbk, the garbled characters disappeared, and the following adjustments were made.
The code is as follows:
$data = eval('return '.iconv('gbk','utf-8',var_export($data,true)).';');
$data is the array that needs to be converted to encoding.
Supplement: LINUX FGETCSV reads GBK data garbled
When the Linux system is using the default settings, it will appear when the gbk csv format file is processed on the Linux server. Garbled characters.
The solution is:
Use the setlocale function to set environment variables. For example, to set the regional settings using gb, you can use the following statement before fgetcsv.
The code is as follows:
setlocale(LC_ALL,array('zh_CN.gbk','zh_CN.gb2312','zh_CN.gb18030'));
Which locales are specifically used? You can use the linux command locale -a to check which
the system supports.The above is the detailed content of How to solve the garbled problem of php fgetcsv. For more information, please follow other related articles on the PHP Chinese website!