導出csv數據很簡單因為csv格式的數據就是一個文本類型了,我們要導入到只要以,號分開它們數據就可以了,然后再利用header輸入csv格式或者excel格式就可以了.
csv文件格式,代碼如下
$exportdata = '規則111,有效期'."\n";
csv文件在php輸出需要使用header告訴瀏覽器格式,代碼如下:
- header("Content-type:application/vnd.ms-excel");
- header("Content-Disposition: attachment; filename=$filename");
例子,代碼如下:
- $exportdata = '規則111,規則222,審222,規222,服2222,規則1,規則2,規則3,匹配字符,設置時間,有效期'."\n";
- $date = date("YmdHis");
- if (!emptyempty($lists)){
- foreach($lists as $key => $value){
- $time = date("Y-m-d_H:i:s", $value['add_time']);
- $exportdata .= "\"\t".$value['Rule_id']."\",\"\t".$value['Rule_name']."\",\"\t".$value['Matching_level']."\",\"\t"."{$value['Rule_action']}"."\",\"\t".$value['Service_type']."\",\"\t".$value['Keyword1']."\",\"\t".$value['Keyword2']."\",\"\t".$value['Keyword3']."\",\"\t".$value['Matching_word']."\",\"\t".$value['Set_time']."\",\"\t".$value['Validation_time']."\"\n";
- }
- }
- $filename = "plcnetinfo_{$date}.csv";
- header("Content-type:application/vnd.ms-excel");
- header("Content-Disposition: attachment; filename=$filename");
- header("Expires: 0");
- header("Pragma: public");
- header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
- header("Cache-Control: public");
- echo(mb_convert_encoding($exportdata,"gb2312","UTF-8"));
下面再整理了一個php+mysql導入csv數據的例子,代碼如下:
- export_csv();
- function export_csv() {
- $filename = date('YmdHis').".csv";//文件名
- header("Content-type:text/csv");
- header("Content-Disposition:attachment;filename=".$filename);
- header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
- header('Expires:0');
- header('Pragma:public');
- echo array_to_string(get_export_data());
- }
- function array_to_string($result) {
- if(emptyempty($result)) {
- return i("沒有符合您要求的數據!^_^");
- }
- $data = '書ID,書名'."\n"; //欄目名稱
- $size_result = sizeof($result);
- for($i = 0 ; $i < $size_result ; $i++) {
- $data .= i($result[$i]['name']).','.i($result[$i]['option'])."\n";
- }
- return $data;
- }
- function get_export_data() {
- $link = mysql_connect('localhost','root','121051xz') or die(mysql_error());
- mysql_select_db('ht');
- mysql_query("set names 'utf8'");//定義編碼
- $sql = 'select * from booklist';
- $result = mysql_query($sql);
- $rowaa = mysql_fetch_array($result);
- $res = array();
- $i = 0;
- while($row = mysql_fetch_array($result)) {
- $res[$i]['name'] = $row['bookid'];
- $res[$i]['option'] = $row['bookname'];
- $i++;
- }
- return $res;
- }
- function i($strInput) {
- return iconv('utf-8','gb2312',$strInput);//頁面編碼為utf-8時使用,否則導出的中文為亂碼
- }
新聞熱點
疑難解答