Introduction: Sometimes we need to make statistics on the collected data and provide display and download on the page. In addition to accessing traditional excel files, it is also important to access CSV files. This article lists the detailed code for these two operations.
Code:
<? Php
$ File = fopen('text.csv ', 'R ');
While ($ data = fgetcsv ($ file) {// read the contents of a row in the CSV each time.
// Print_r ($ data); // This is an array. To obtain each data, access the array subscript.
$ Goods_list [] = $ data;
}
// Print_r ($ goods_list );
Echo $ goods_list [0] [1];
Fclose ($ file );
?>
In practice, you often need to download some data from the website to a CSV file for later viewing.
Or use CSV to upload data in batches.
In this case, we need to read and write CSV files.
Php CSV read Operations
Code:
<? Php
$ File = fopen ('d:/file/file.csv ', 'R ');
While ($ data = fgetcsv ($ file) {// read the contents of a row in the CSV each time.
Print_r ($ data); // This is an array. To obtain each data, access the array subscript.
}
Fclose ($ file );
?>
<? Php $ file = fopen ('d:/file/file.csv ', 'R'); while ($ data = fgetcsv ($ file )) {// print_r ($ data), which reads a line of content in the CSV each time; // This is an array to obtain each data, access the array subscript} fclose ($ file);?>
CSV write operation
Code:
<? Php
$ Fp = fopen ('d:/file/file.csv ', 'w ');
Fputcsv ($ fp, array ('aaa', 'bbb ', 'cccccc'); // www.jbxue.com
Fputcsv ($ fp, array ('mmm', 'yyy', 'hahaha'); // fputcsv can be implemented through array loops.
Fclose ($ fp );
?>
<? Php $ fp = fopen ('d:/file/file.csv ', 'w ');
Fputcsv ($ fp, array ('aaa', 'bbb ', 'cccccc '));
Fputcsv ($ fp, array ('mmm', 'yyy', 'hahaha'); // fputcsv can be implemented using an array loop ($ fp );
?>
Output CSV (download function)
Code:
<? 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, china/n ";
Echo "2, us, America/n ";
?>
Output excel (download function)
Header ("Content-type: application/vnd. ms-excel ");
Header ("Content-Disposition: filenameappsphp100.xls ");
Echo "id, areaCode, areaName/n ";
Echo "1, cn, china/n ";
Echo "2, us, America/n ";