Home >Backend Development >PHP Tutorial >Detailed explanation of PHP's reading, writing, and output downloading operations for csv files_PHP Tutorial

Detailed explanation of PHP's reading, writing, and output downloading operations for csv files_PHP Tutorial

WBOY
WBOYOriginal
2016-07-21 14:59:541056browse

Copy code The code is as follows:

$file = fopen('text.csv', 'r');

while ($data = fgetcsv($file)) { //Read one line of content in the CSV each time
//print_r($data); //This is an array, to get each piece of data, Just access the array subscript
$goods_list[] = $data;
}
//print_r($goods_list);
echo $goods_list[0][1];
fclose( $file);
?>


In actual work, it is often necessary to download some data on the website into a CSV file for easy viewing later.
Or you can use CSV to perform some batch upload work.
At this time we need to read and write CSV.

CSV reading operation

Copy code The code is as follows:

$file = fopen('D:/file/file.csv','r');
while ($data = fgetcsv($file)) { //Read one line of content in CSV each time
                                                                                           



CSV writing operation


Copy code

The code is as follows: $fp = fopen('d:/file/file.csv', 'w');
fputcsv($fp,array('aaa','bbb','cccc'));
fputcsv($fp,array('mmm','yyy','haha')); //fputcsv can be implemented by array looping
fclose($fp);
?>




Output CSV (download function)


Copy code

The code is as follows: 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:filename=php100.xls");
echo "id, areaCode,areaName/n"; 
echo "1,cn,china/n" ; 
echo "2,us,America/n"; >

http://www.bkjia.com/PHPjc/328114.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/328114.htmlTechArticleCopy the code as follows: ?php $file = fopen('text.csv','r'); while ($data = fgetcsv($file)) { //Read one line of content in CSV each time //print_r($data); //This is an array, to get...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn