Import and Export CSV files in PHP

Source: Internet
Author: User
Tags parse csv file
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 document uses PHP and mysql to import and export CSV data.

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 document uses PHP and mysql to import and export CSV data.

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.

The Code is as follows:



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:


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:


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.

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

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.