參考網址:
php對csv文件的常用操作集合
http://blog.xhbin.com/archives/748
1,下載CSV格式文檔
唯一需要特別注意的是編碼。
1 <? 2 include_once("conn/conn.php");//連接數據庫 3 4 $EXCEL_OUT="id,title,info\n";//生成字段 5 6 $query="select * from tb_info";//需要生成的數據查詢語句 7 $result=mysql_query($query); 8 while($ROW=mysql_fetch_array($result)) 9 { 10 $id=$ROW["id"]; 11 $title=$ROW["title"]; 12 $content=$ROW["content"]; 13 14 $EXCEL_OUT.=iconv('UTF-8','GB2312',"$id,$title,$content\n"); 15 } 16 17 header("Content-type:text/csv"); 18 header("Content-Disposition:attachment;filename=生成文件名稱.csv"); //“生成文件名稱”=自定義 19 header('Cache-Control:must-revalidate,post-check=0,pre-check=0'); 20 header('Expires:0'); 21 header('Pragma:public'); 22 echo $EXCEL_OUT; 23 ?>
2,生成.csv文件(不下載)
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 10 fwrite($fp,iconv('UTF-8','GB2312',$data_str)); //寫入數據 11 fclose($fp); //關閉文件句柄 12 echo "生成成功"; 13 } 14 echo "<br>"; 15 echo "<a href='?action=make'>生成csv文件</a>"; 16 17 18 //批注:由於涉及文件讀寫,所以有權限要求。比如通過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)