PHP read, write to csv file, output download operation

Source: Internet
Author: User
Tags vars

In the actual work, many times need to download some of the data on the site into a CSV file, easy to view later.

Or use CSV to do some batch upload work.

At this point, we need to read and write the CSV.

1.CSV Read operation

[PHP]View Plaincopy
    1. <?php
    2. $file = fopen (' d:/file/file.csv ',' R ');
    3. While ($data = fgetcsv ($file)) { //reads a row of CSV each time
    4. Print_r ($data); //This is an array, to get every data, access the array subscript can
    5. }
    6. Fclose ($file);
    7. ?>

2.CSV Write operation

[PHP]View Plaincopy
    1. <?php
    2. $fp = fopen (' d:/file/file.csv ', ' W ');
    3. fputcsv ($fp,Array (' AAA ',' BBB ',' CCCC '));
    4. fputcsv ($fp,array (' mmm ',' yyy ',' haha ')); //fputcsv can be implemented in the form of an array loop
    5. Fclose ($fp);
    6. ?>

3. Output csv (download function)

[PHP]View Plaincopy
    1. <?php
    2. Header ("Content-type:text/csv");
    3. Header ("content-disposition:attachment;  Filename=test.csv ");
    4. Header (' cache-control:must-revalidate,post-check=0,pre-check=0 ');
    5. Header (' expires:0 ');
    6. Header (' pragma:public ');
    7. echo "id,areacode,areaname/n";
    8. echo "1,CN

PHP read, write to csv file, output download operation

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.