PHP生成CSV格式文件
阿新 • • 發佈:2018-12-31
1,下載CSV格式文件
唯一需要特別注意的是編碼。Php程式碼
- <?
- include_once("conn/conn.php");//連線資料庫
- $EXCEL_OUT="id,title,info\n";//生成欄位
- $query="select * from tb_info";//需要生成的資料查詢語句
- $result=mysql_query($query);
- while($ROW=mysql_fetch_array($result))
- {
- $id=$ROW["id"];
- $title=$ROW["title"];
-
$content
- $EXCEL_OUT.=iconv('UTF-8','GB2312',"$id,$title,$content\n");
- }
- header("Content-type:text/csv");
- header("Content-Disposition:attachment;filename=生成檔名稱.csv"); //“生成檔名稱”=自定義
- header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
- header('Expires:0');
-
header('Pragma:public'
- echo $EXCEL_OUT;
- ?>
2,生成.csv檔案(不下載)
Php程式碼
- $action = $_GET['action'];
- if ($action=='make'){
- $fp = fopen("csv.csv","a"); //開啟csv檔案,如果不存在則建立
- $data_arr1 = array("10001","10002","10003","10004","公司"); //第一行資料
- $data_arr2 = array("20001","20002","20003","20004","中午"); //第二行資料
-
$data_str1 = implode(",",$data_arr1
- $data_str2 = implode(",",$data_arr2); //用 ' 分割成字串
- $data_str = $data_str1."\r\n".$data_str2."\r\n"; //加入換行符
- fwrite($fp,iconv('UTF-8','GB2312',$data_str)); //寫入資料
- fclose($fp); //關閉檔案控制代碼
- echo "生成成功";
- }
- echo "<br>";
- echo "<a href='?action=make'>生成csv檔案</a>";
- //批註:由於涉及檔案讀寫,所以有許可權要求。比如通過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)