Solution of Garbled Code in php Using fgetcsv to Read csv File

  • 2021-07-26 07:13:04
  • OfStack

This article describes the example of php using fgetcsv reading csv file garbled solution. Share it for your reference. The specific analysis is as follows:

1 Generally speaking, most of the garbled codes encountered in php are coding problems. Here, we analyze the causes and solutions of garbled codes in fgetcsv reading csv files with examples.

Examples are 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 with ansi code, which should be gbk code for Chinese operating system environment. By manually changing the browser character code to gbk, the garbled code disappeared, and the following adjustments were made.

$data = eval('return '.iconv('gbk','utf-8',var_export($data,true)).';');

$data is the array that needs to be transcoded.

Supplement: LINUX FGETCSV reads GBK data garbled

When the Linux system is used as the default setting, the csv format file of gbk will be garbled when processed on the Linux server.

The solution is:

Use the setlocale function to set the environment variables. For example, to set the locale using gb, you can use the following statement before fgetcsv.

setlocale(LC_ALL,array('zh_CN.gbk','zh_CN.gb2312','zh_CN.gb18030'));

You can use the linux command locale-a to see what the system supports

I hope this article is helpful to everyone's PHP programming.


Related articles: