1. 程式人生 > >PHP生成CSV格式文件

PHP生成CSV格式文件

1,下載CSV格式文件 

唯一需要特別注意的是編碼。 
Php程式碼  收藏程式碼
  1. <?  
  2. include_once("conn/conn.php");//連線資料庫  
  3. $EXCEL_OUT="id,title,info\n";//生成欄位  
  4. $query="select * from tb_info";//需要生成的資料查詢語句  
  5. $result=mysql_query($query);  
  6. while($ROW=mysql_fetch_array($result))  
  7. {  
  8.    $id=$ROW["id"];  
  9.    $title=$ROW["title"];  
  10.    $content
    =$ROW["content"];  
  11.     $EXCEL_OUT.=iconv('UTF-8','GB2312',"$id,$title,$content\n");  
  12. }  
  13. header("Content-type:text/csv");   
  14. header("Content-Disposition:attachment;filename=生成檔名稱.csv"); //“生成檔名稱”=自定義  
  15. header('Cache-Control:must-revalidate,post-check=0,pre-check=0');   
  16. header('Expires:0');   
  17. header('Pragma:public'
    );   
  18. echo $EXCEL_OUT;  
  19. ?>  


2,生成.csv檔案(不下載) 
Php程式碼  收藏程式碼
  1. $action = $_GET['action'];  
  2. if ($action=='make'){  
  3.  $fp = fopen("csv.csv","a"); //開啟csv檔案,如果不存在則建立  
  4.  $data_arr1 = array("10001","10002","10003","10004","公司"); //第一行資料  
  5.  $data_arr2 = array("20001","20002","20003","20004","中午"); //第二行資料  
  6.  $data_str1 = implode(",",$data_arr1
    ); //用 ' 分割成字串  
  7.  $data_str2 = implode(",",$data_arr2); //用 ' 分割成字串  
  8.  $data_str = $data_str1."\r\n".$data_str2."\r\n"//加入換行符  
  9.  fwrite($fp,iconv('UTF-8','GB2312',$data_str)); //寫入資料  
  10.  fclose($fp); //關閉檔案控制代碼  
  11.  echo "生成成功";  
  12. }  
  13. echo "<br>";  
  14. echo "<a href='?action=make'>生成csv檔案</a>";   
  15. //批註:由於涉及檔案讀寫,所以有許可權要求。比如通過http方式是無法建立該檔案的。(可以通過php file.php方式)  




附:iconv 用法 
string iconv ( string $in_charset , string $out_charset , string $str ) 
iconv — Convert string to requested character encoding 

引數: 
1,in_charset  輸入字串的編碼 
2,out_charset 輸出字串的編碼 
   If you append the string //TRANSLIT to out_charset transliteration is activated. This means that when a character can't be represented in the target charset, it can be approximated through one or several similarly looking characters. If you append the string //IGNORE, characters that cannot be represented in the target charset are silently discarded. Otherwise, str is cut from the first illegal character and an E_NOTICE is generated. 

3,str  被轉碼的字串 

返回值: 
返回轉碼後的字串或false(返回失敗時)。 

可能會用到兩個可選的輔助引數:IGNORE和TRANSLIT 
例如:iconv("UTF-8","GB2312//IGNORE",$data)