Php uses fgetcsv to read csv files with garbled characters,
This example describes how php uses fgetcsv to read csv files with garbled characters. Share it with you for your reference. The specific analysis is as follows:
In general, encoding is the most common case of Garbled text in php. Here we analyze the cause and solution of Garbled text in fgetcsv reading csv files.
Example:
Copy codeThe 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, 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.
Copy codeThe Code is as follows: $ data = eval ('Return '. iconv ('gbk', 'utf-8', 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.
Copy codeThe Code is as follows: 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?
I hope this article will help you with PHP programming.