Php uses fgetcsv to read csv file garbled solution

Source: Internet
Author: User
Tags locale

Example

 

The code is as follows: Copy code

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, it should be gbk encoding. By manually changing the browser character encoding to gbk, garbled characters disappear, at that time, the following adjustments were made.

The code is as follows: Copy code

$ Data = eval ('Return '. iconv ('gbk', 'utf-8 & prime;, var_export ($ data, true )).';');

$ Data is the array to be converted into encoding.

Supplement: linux fgetcsv garbled data reading GBK

When the Linux system uses the default settings, garbled characters will occur when the csv format files of gbk are processed on the Linux server.
Solution:
Use the setlocale function to set environment variables. For example, you can use the following statement before fgetcsv to set the region with gb.

The code is as follows: Copy code

Setlocale (LC_ALL, array ('zh _ CN. Gbk', 'zh _ CN. gb2312 ', 'zh _ CN. Gb18030 '));

Which locale can be used? Use the linux command locale-a to check which supported by the system?

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.