Home  >  Article  >  Backend Development  >  How to solve the garbled problem of php fgetcsv

How to solve the garbled problem of php fgetcsv

藏色散人
藏色散人Original
2020-07-27 10:06:083941browse

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.

How to solve the garbled problem of php fgetcsv

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(&#39;return &#39;.iconv(&#39;gbk&#39;,&#39;utf-8&#39;,var_export($data,true)).&#39;;&#39;);

$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(&#39;zh_CN.gbk&#39;,&#39;zh_CN.gb2312&#39;,&#39;zh_CN.gb18030&#39;));

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn