Example of data import and CSV file download using PHP

Source: Internet
Author: User

Import and Export CSV files

Code:

The code is as follows: Copy code

Class csv
{
Private $ resource;

/**
* @ Param string $ fileName File path
* @ Param string $ mode file access type: w: write, r: Read-only
*/
Public function _ construct ($ fileName, $ mode)
 {
$ This-> resource = fopen ($ fileName, $ mode );
 }

Public function _ destruct ()
 {
Fclose ($ this-> resource );
 }

/**
* Import CSV www.111cn.net
* @ Param array $ data
* @ Return int
*/
Public function export ($ data)
 {
Fputcsv ($ this-> resource, $ data );
 }

/**
* Export CSV
* @ Return array
*/
Public function import ()
 {
$ Tmp = array ();
While ($ data = fgetcsv ($ this-> resource ))
  {
$ Tmp [] = $ data;
  }

Return $ tmp;
 }
}

Here we mainly use the php fgetcsv function and fputcsv function.


CSV file download

The code is as follows: Copy code

Function exportUserTask ()
{
// Obtain database data
/*
* $ Result = array (
* Array (value1, value2, value3, value4, value5, value6 ),
* Array (value1, value2, value3, value4, value5, value6 ),
*);
*/

$ Handle = fopen ('php: // output', "w ");
Header ('content-Type: application/csv ');
Header ('content-Disposition: attachment; filename = "test.csv "');

// Header www.111cn.net
Fputcsv ($ handle, array ('User uid', 'username', 'in progress ', 'completed', 'failed, 'total '));

Foreach ($ result as $ value)
 {
Fputcsv ($ handle, $ value );
 }

Fclose ($ handle );
}

Note that Chinese characters are garbled during data import and export. This is mainly due to the data encoding format problem. The data is transcoded according to the actual situation.

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.