This article will introduce the fgetcsv function to the specific functions of the mysql database for importing csv files. You can also find a solution to Chinese garbled characters.
When processing a large volume of excel Data to the mysql database, use the fgetcsv function provided by php to first obtain data from the csv file row by row and then import the data to the database with SQL statements. If garbled characters occur, you can use the iconv function for transcoding.
Sample Code:
The Code is as follows: |
Copy code |
<? Php $ Row = 1; $ Handle = fopen ("test.csv", "r "); While ($ data = fgetcsv ($ handle, 1000, ",") {// 1000 is the total number of rows in the csv file, and the comma is the data Separator. Both parameters can be ignored. $ Num = count ($ data ); Echo "<p> row $ row contains $ num fields. <Br> n "; $ Row ++; For ($ c = 0; $ c <$ num; $ c ++ ){ Echo $ data [$ c]. "<br> n "; } } Fclose ($ handle ); ?> |
Chinese characters garbled during mysql Import
When reading and uploading csv files in a common method on the Internet into the mysql database, garbled characters are displayed in Chinese. Even if the data is still garbled after being transcoded using the iconv function, you can use the setlocale () function:
This function is used to configure the region information after reading and writing csv data, first use this function to define, for example, my csv file is a BOM-free UTF-8 format, the following functions are used for definition:
The Code is as follows: |
Copy code |
Setlocale (LC_ALL, 'zh _ CN. utf8 ′); |
Then, use the iconv function to perform subsequent operations such as transcoding and receiving data content.