[Advanced technology] how to 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 introduces how to import and export CSV data using PHP and mysq. 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`) 

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.

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 == 'export') {// Export CSV
    // Export processing

Process for importing a CSV file: check the validity of the csv file (this document ignores)-> open and read and parse the csv file

Items in the field-> loop to obtain the value of each field-> batch add to the data table-> complete.

if ($ action == 'import') {// Import CSV
    $ filename = $ _FILES ['file'] ['tmp_name'];
    if (empty ($ filename)) {
        echo 'Please select a CSV file to import! ';
    $ handle = fopen ($ filename, 'r');
    $ result = input_csv ($ handle); // parse csv
    $ len_result = count ($ result);
    if ($ len_result == 0) {
        echo 'No data! ';
    for ($ i = 1; $ i <$ len_result; $ i ++) {// Recycle each field value
        $ 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"); // Bulk insert into the data table
    if ($ query) {
        echo 'Import success! ';
    } 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]; 
    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.

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 the header information-> export the file (download) to The Local.

} elseif ($ action == 'export') {// 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 with commas
     $ filename = date ('Ymd'). '. csv'; // Set 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) { 
    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 [advanced technology] how to import and export CSV file content in PHP. For more information, see PHP Chinese website (www.php1.cn )!

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.