最新消息: 新版网站上线了!!!

PHP导出数据到CSV文件函数 csv_export()

  1. /** 
  2.  * 导出数据到CSV文件 
  3.  * 
  4.  * @param array $data 二维数组(模拟数据表记录) 
  5.  * @param array $titleList 标题数组列表 
  6.  * @param string $fileName CSV文件名 
  7.  */ 
  8. function csv_export(&$data$titleList = array(), $fileName = ''
  9.     ini_set("max_execution_time""3600"); 
  10.     $csvData = ''
  11.  
  12.     // 标题 
  13.     $nums = count($titleList); 
  14.     for ($i = 0; $i < $nums - 1; $i++) 
  15.     { 
  16.         $csvData .= '"' . $titleList[$i] . '",'
  17.     } 
  18.     $csvData .= '"' . $titleList[$nums - 1] . "\"\r\n"
  19.  
  20.     foreach ($data as $key => $row
  21.     { 
  22.         $i = 0; 
  23.         foreach ($row as $_key => $_val
  24.         { 
  25.             $_val = str_replace("\"""\"\""$_val); 
  26.             if ($i < ($nums - 1)) 
  27.             { 
  28.                 $csvData .= '"' . $_val . '",'
  29.             } 
  30.             elseif ($i == ($nums - 1)) 
  31.             { 
  32.                 $csvData .= '"' . $_val . "\"\r\n"
  33.             } 
  34.             $i++; 
  35.         } 
  36.         unset($data[$key]); 
  37.     } 
  38.  
  39.     $csvData = mb_convert_encoding($csvData"cp936""UTF-8"); 
  40.     $fileName = emptyempty($fileName) ? date('Y-m-d-H-i-s', time()) : $fileName
  41.     $fileName = $fileName . '.csv'
  42.     header("Content-type:text/csv;"); 
  43.     header("Content-Disposition:attachment;filename=" . $fileName); 
  44.     header('Cache-Control:must-revalidate,post-check=0,pre-check=0'); 
  45.     header('Expires:0'); 
  46.     header('Pragma:public'); 
  47.     echo $csvData
  48.     die(); 

示例:

 

  1. $data = array
  2.     array
  3.         'name' => 'jake'
  4.         'score' => 80, 
  5.         'grade' => 'A' 
  6.     ), 
  7.     array
  8.         'name' => 'jin'
  9.         'score' => 70, 
  10.         'grade' => 'A' 
  11.     ), 
  12.     array
  13.         'name' => 'john'
  14.         'score' => 80, 
  15.         'grade' => 'A' 
  16.     ), 
  17.     array
  18.         'name' => 'ben3'
  19.         'score' => 203, 
  20.         'grade' => 'B3' 
  21.     ) 
  22. ); 
  23.  
  24. $titleList = array('姓名''总分''等级'); 
  25. $fileName = '高三(3)班 7 月份考试结果'
  26.  
  27. csv_export($data$titleList$fileName); 

 

转载请注明:谷谷点程序 » PHP导出数据到CSV文件函数 csv_export()