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: |
Copy code |
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.
The code is as follows: |
Copy code |
<Form id = "addform" action = "do. php? Action = import "method =" post "enctype =" multipart/form-data "> <P> select the CSV file to be imported: <br/> <input type = "file" name = "file"> <input type = "submit" Class = "btn" value = "import CSV"> <Input type = "button" class = "btn" value = "export CSV" onclick = "window. location. href = 'Do. php? Action = export' "> </p> </Form> |
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:
The code is as follows: |
Copy code |
Include_once ("connect. php"); // connect to the database $ 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: |
Copy code |
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: |
Copy code |
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: |
Copy code |
... } 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: |
Copy code |
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.