PHP imports and exports CSV files to the mysql database. Because of work requirements, we need to export mysql data into csv files, and then we need to use php to import csv files to the mysql database, next I will introduce to you that we need to export data from mysql into a csv file because of work requirements. then, we need to use php to import csv files to the mysql database for the data provided by sellers, next, I will introduce PHP code for importing and exporting CSV files to mysql database. For more information, see.
The following is a simple example.
Prepare the mysql data table first. assume that the project contains a student information table student with the id, name, sex, and age information to record the student name, gender, and age respectively.
The code is as follows: |
|
Create table 'student '( 'Id' int (11) not null auto_increment, 'Name' varchar (50) not null, 'Sex 'varchar (10) not null, 'Age' smallint (3) not null default '0 ', Primary key ('id ') ) ENGINE = MyISAM default charset = utf8; |
We also need an html interaction page to place the import form and export button.
After selecting the local csv file, Click import and submit it to do. php? Action = import processing, and click Export to request the address do. php? Action = export to export data.
1. import CSV
Do. php processes the import and export processes based on get parameters. The php structure is as follows:
Include_once ("connect. php"); // connect to the database
The code is as follows: |
|
$ Action = $ _ GET ['action']; If ($ action = 'import') {// import CSV // Import } Elseif ($ action = 'port') {// export CSV // Export } |
Process for importing a CSV file: check the validity of the csv file (this document ignores) -> open the fields in the csv file and parse them.-> obtain the values of each field cyclically-> Add them to the data table in batches-> complete.
The code is as follows: |
|
If ($ action = 'import') {// import CSV $ Filename = $ _ FILES ['file'] ['tmp _ name']; If (empty ($ filename )){ Echo 'select the CSV file to import! '; Exit; } $ Handle = fopen ($ filename, 'r '); $ Result = input_csv ($ handle); // Parse csv $ Len_result = count ($ result ); If ($ len_result = 0 ){ Echo 'no data! '; Exit; } For ($ I = 1; $ I <$ len_result; $ I ++) {// Obtain field values cyclically $ Name = iconv ('gb2312', 'utf-8', $ result [$ I] [0]); // Chinese transcoding $ Sex = iconv ('gb2312', 'utf-8', $ result [$ I] [1]); $ Age = $ result [$ I] [2]; $ Data_values. = "('$ name',' $ sex', '$ age '),"; } $ Data_values = substr ($ data_values, 0,-1); // remove the last comma Fclose ($ handle); // Close the pointer $ Query = mysql_query ("insert into student (name, sex, age) values $ data_values"); // insert data tables in batches If ($ query ){ Echo 'import successful! '; } Else { Echo 'import failed! '; } } |
Note that the fgetcsv function provided by php can easily process csv. you can use this function to read a row from the file pointer and parse the CSV field. The following functions parse csv file fields and return them as arrays.
The code is as follows: |
|
Function input_csv ($ handle ){ $ Out = array (); $ N = 0; While ($ data = fgetcsv ($ handle, 10000 )){ $ Num = count ($ data ); For ($ I = 0; $ I <$ num; $ I ++ ){ $ Out [$ n] [$ I] = $ data [$ I]; } $ N ++; } Return $ out; } |
In addition, when we import data to the database, we use batch inserts instead of individual inserts. Therefore, when constructing SQL statements, we need to perform some processing. see the code.
2. export CSV
We know that a csv file is a plain text file consisting of commas (,). you can open it in excel, and the effect is the same as that in xls tables.
Export CSV processing process: Read the student information table-> Create a comma-separated field information loop record-> set header information-> export a file (download) to a local
The code is as follows: |
|
... } Elseif ($ action = 'port') {// export CSV $ Result = mysql_query ("select * from student order by id asc "); $ Str = "name, gender, age n "; $ Str = iconv ('utf-8', 'gb2312', $ str ); While ($ row = mysql_fetch_array ($ result )){ $ Name = iconv ('utf-8', 'gb2312', $ row ['name']); // Chinese transcoding $ Sex = iconv ('utf-8', 'gb2312', $ row ['sex']); $ Str. = $ name. ",". $ sex. ",". $ row ['age']. "n"; // separate them with commas (,). } $ Filename = date('ymd'0000.'.csv '; // you can specify a file name. Export_csv ($ filename, $ str); // export } |
To export data to a local directory, you need to modify the header information. the code is as follows:
The code is as follows: |
|
Function export_csv ($ filename, $ data ){ Header ("Content-type: text/csv "); Header ("Content-Disposition: attachment; filename =". $ filename ); Header ('cache-Control: must-revalidate, post-check = 0, pre-check = 0 '); Header ('expires: 0 '); Header ('pragma: public '); Echo $ data; } |
Pay attention to the process of import and export, because we use a unified UTF-8 encoding, encounter Chinese characters must remember to transcode, otherwise there may be Chinese garbled.
PHP import and export CSV file download: http://file.bKjia. c0m/download/2013/05/15/importCSV.rar
...