php快速匯出csv格式資料程式碼

來源:互聯網
上載者:User

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 (!empty($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資料的例子

 代碼如下 複製代碼

<?php
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(empty($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時使用,否則匯出的中文為亂碼
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.