php導出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時使用,否則導出的中文為亂碼
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM