Import and Export CSV files using php

Source: Internet
Author: User
Tags parse csv file
This article mainly introduces how to import and export CSV files in php, which has some reference value. if you need it, you can refer to the project development process, most of the time, you 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.
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 (emptyempty ($ 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.

The above is all the content of this article. I hope this article will help you with php programming.

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.