errno) { die('Connect Error' . $mysqli->error); } $mysqli->set_charset('UTF8'); 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 i($strInput) { return iconv('utf-8', 'gb2312', $strInput);//页面编码为utf-8时使用,否则导出的中文为乱码 } function array_to_string($result) { if (empty($result)) { return i("没有符合您要求的数据!"); } //表头 $data = iconv('utf-8', 'gb2312', "kh_name,kh_address") . "\r\n"; $size_result = sizeof($result); for ($i = 0; $i < $size_result; $i++) { $data .= i($result[$i]['kh_name']) . ',' . i($result[$i]['kh_address']) . "\n"; } return $data; } function get_export_data() { $sql = "SELECT kh_name,kh_address FROM bs_kehu"; global $mysqli; $result = $mysqli->query($sql); $res = array(); $i = 0; while ($row = $result->fetch_array(MYSQLI_ASSOC)) { $res[$i]['kh_name'] = $row['kh_name']; $res[$i]['kh_address'] = $row['kh_address']; $i++; } return $res; }