In php, the fgetcsv function imports csv files into mysql database _ PHP Tutorial

Source: Internet
Author: User
Tags mysql import
In php, the fgetcsv function imports the csv file into the mysql database. 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. This article describes how to import csv files into mysql database using the fgetcsv function. 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:

$ 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"

Row $ row contains $ num fields.
N ";
$ Row ++;
For ($ c = 0; $ c <$ num; $ c ++ ){
Echo $ data [$ c]."
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:

Setlocale (LC_ALL, 'zh _ CN. utf8 ′);

Then, use the iconv function to perform subsequent operations such as transcoding and receiving data content.

Bytes. Processing large batches...

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.