The fgetcsv function in php imports csv files to the mysql database.

Source: Internet
Author: User
Tags mysql import

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.

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.