|
復(fù)制代碼 代碼如下:
<?php
$file = fopen('text.csv','r');
while ($data = fgetcsv($file)) { //每次讀取CSV里面的一行內(nèi)容
//print_r($data); //此為一個(gè)數(shù)組,要獲得每一個(gè)數(shù)據(jù),訪(fǎng)問(wèn)數(shù)組下標(biāo)即可
$goods_list[] = $data;
}
//print_r($goods_list);
echo $goods_list[0][1];
fclose($file);
?>
在實(shí)際工作中,很多時(shí)候需要把網(wǎng)站上的一些數(shù)據(jù)下載到CSV文件里,方便以后查看。
亦或者是用CSV進(jìn)行一些批量的上傳工作。
這個(gè)時(shí)候我們就需要對(duì)CSV進(jìn)行讀寫(xiě)操作。
CSV的讀取操作
復(fù)制代碼 代碼如下:
<?php
$file = fopen('D:/file/file.csv','r');
while ($data = fgetcsv($file)) { //每次讀取CSV里面的一行內(nèi)容
print_r($data); //此為一個(gè)數(shù)組,要獲得每一個(gè)數(shù)據(jù),訪(fǎng)問(wèn)數(shù)組下標(biāo)即可
}
fclose($file);
?>
<?php $file = fopen('D:/file/file.csv','r'); while ($data = fgetcsv($file)) { //每次讀取CSV里面的一行內(nèi)容 print_r($data); //此為一個(gè)數(shù)組,要獲得每一個(gè)數(shù)據(jù),訪(fǎng)問(wèn)數(shù)組下標(biāo)即可 } fclose($file); ?>
CSV的寫(xiě)入操作
復(fù)制代碼 代碼如下:
<?php
$fp = fopen('d:/file/file.csv', 'w');
fputcsv($fp,array('aaa','bbb','cccc'));
fputcsv($fp,array('mmm','yyy','haha')); //fputcsv可以用數(shù)組循環(huán)的方式進(jìn)行實(shí)現(xiàn)
fclose($fp);
?>
<?php $fp = fopen('d:/file/file.csv', 'w'); fputcsv($fp,array('aaa','bbb','cccc')); fputcsv($fp,array('mmm','yyy','haha')); //fputcsv可以用數(shù)組循環(huán)的方式進(jìn)行實(shí)現(xiàn) fclose($fp); ?>
輸出CSV(下載功能)
復(fù)制代碼 代碼如下:
<?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";
?>
輸出excel(下載功能)
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";
php技術(shù):php對(duì)csv文件的讀取,寫(xiě)入,輸出下載操作詳解,轉(zhuǎn)載需保留來(lái)源!
鄭重聲明:本文版權(quán)歸原作者所有,轉(zhuǎn)載文章僅為傳播更多信息之目的,如作者信息標(biāo)記有誤,請(qǐng)第一時(shí)間聯(lián)系我們修改或刪除,多謝。