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.

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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.