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
- <?php
- $file = fopen (' d:/file/file.csv ',' R ');
- While ($data = fgetcsv ($file)) { //reads a row of CSV each time
- Print_r ($data); //This is an array, to get every data, access the array subscript can
- }
- Fclose ($file);
- ?>
2.CSV Write operation
[PHP]View Plaincopy
- <?php
- $fp = fopen (' d:/file/file.csv ', ' W ');
- fputcsv ($fp,Array (' AAA ',' BBB ',' CCCC '));
- fputcsv ($fp,array (' mmm ',' yyy ',' haha ')); //fputcsv can be implemented in the form of an array loop
- Fclose ($fp);
- ?>
3. Output csv (download function)
[PHP]View Plaincopy
- <?php
- Header ("Content-type:text/csv");
- Header ("content-disposition:attachment; Filename=test.csv ");
- Header (' cache-control:must-revalidate,post-check=0,pre-check=0 ');
- Header (' expires:0 ');
- Header (' pragma:public ');
- echo "id,areacode,areaname/n";
- echo "1,CN
PHP read, write to csv file, output download operation