php csv文件的讀取,寫入,輸出下載操做詳解

php對csv文件的讀取,寫入,輸出下載操做。
代碼:
<?php   
    $file = fopen('text.csv','r');
    while ($data = fgetcsv($file)) {    //每次讀取CSV裏面的一行內容   
   //print_r($data); //此爲一個數組,要得到每個數據,訪問數組下標便可
   $goods_list[] = $data;
    }
//print_r($goods_list);
echo $goods_list[0][1];
    fclose($file);   
?>
在實際工做中,不少時候須要把網站上的一些數據下載到CSV文件裏,方便之後查看。
亦或者是用CSV進行一些批量的上傳工做。
這個時候咱們就須要對CSV進行讀寫操做。
CSV的讀取操做
<?php    
$file = fopen('D:/file/file.csv','r');    
while ($data = fgetcsv($file)) {    //每次讀取CSV裏面的一行內容    
  print_r($data); //此爲一個數組,要得到每個數據,訪問數組下標便可    
}  www.jbxue.com
fclose($file);    
?>
<?php $file = fopen('D:/file/file.csv','r'); while ($data = fgetcsv($file)) { //每次讀取CSV裏面的一行內容 print_r($data); //此爲一個數組,要得到每個數據,訪問數組下標便可 } fclose($file); ?>
CSV的寫入操做
<?php    
  $fp = fopen('d:/file/file.csv', 'w');    
  fputcsv($fp,array('aaa','bbb','cccc'));    
  fputcsv($fp,array('mmm','yyy','haha'));   //fputcsv能夠用數組循環的方式進行實現    
   fclose($fp);    
?>
輸出CSV(下載功能)
<?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";
相關文章
相關標籤/搜索