Import and Export CSV files in PHP,
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.
Copy codeThe 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.
Copy codeThe Code is as follows:
<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:
Copy codeThe Code is as follows:
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.
Copy codeThe Code is as follows:
If ($ action = 'import') {// import CSV
$ Filename = $ _ FILES ['file'] ['tmp _ name'];
If (emptyempty ($ 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 the 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.
Copy codeThe 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
Copy codeThe 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:
Copy codeThe 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.
Now, this article explains how to import and export excel and xml using PHP and mysql.