[Code implementation] use PHP to import and export CSV files

Source: Internet
Author: User
Tags parse csv file
[Code implementation] use PHP to import and export CSV file address: http://www.phpthinking.com/archives/558

During project development, you often need to import an external CSV file to a database or export the data as a CSV file. how can this problem be solved? This article uses PHP and mysql to import and export CSV data.

Download source code

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.

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 $ action =$ _ GET ['action']; if ($ action = 'import ') {// import CSV // import processing} elseif ($ action = 'port') {// export CSV // export processing}

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.

If ($ action = 'import') {// import CSV $ filename = $ _ FILES ['file'] ['tmp _ name']; if (empty ($ filename) {echo 'select the CSV file to be imported! '; Exit ;}$ handle = fopen ($ filename, 'r'); $ result = input_csv ($ handle); // Parse csv $ len_result = count ($ result ); if ($ len_result = 0) {echo 'has 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 'is imported successfully! ';} 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.

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

...} 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"; // separated by commas (,)} $ filename = date('Ymd').'.csv '; // sets the 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:

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.

Related Article

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.