*PHP程式設計 -- 用CSV檔案作資料備分:
這是一個簡單又好用的CSV檔案資料備分程式,
中文也可以正常顯示。
<?php
require "conn.php";
require "key.php";
$ListColums =array('序號', '姓名', '留言內容', '電話','電子郵件','地址','IP位置','留言時間','回覆內容','回覆時間'); //欄位名稱
$filename = "contact.csv";
$file = fopen($filename,"wt");
fputcsv($file,$ListColums);
$sql="select contact.*,contact_reply.reply,contact_reply.dater from contact left join contact_reply on contact.id=contact_reply.cid order by contact.date desc";
$result = mysql_query($sql);
$num=mysql_num_rows($result);
if($num==0){
// echo '<script type="text/javascript">alert("無資料可匯出!");location.href="contact_list.php";</script>';
// echo '<script>alert("無資料可匯出!");</script>';
header("Location: contact_list.php?c=1");
exit;
}
function cube($n){
return preg_replace( '!<br.*>!iU', "\n", $n );
}
for ($i = 0; $i < mysql_num_rows($result); $i++) {
$dataArray[$i] = mysql_fetch_assoc($result);
$dataArray[$i] = array_map("cube", $dataArray[$i]);
}
foreach ($dataArray as $line) { //每筆資料代入
fputcsv($file,$line);
}
fclose($file);
//csv檔由utf-8轉big5:Excel為big5編碼
$temp = file_get_contents('contact.csv');
$temp = iconv('utf-8','big5',$temp);
file_put_contents("contact.csv",$temp);
header("Content-Type: application/csv");
header("Content-Disposition: attachment;Filename=".$filename);
readfile($filename);
unlink($filename);
?>