<?php
Header (' Content-type:text/html;charset=utf-8 ');
$mysqli = new mysqli (' localhost ', ' root ', ' ', ' C ');
if ($mysqli->errno) {
Die (' Connect Error '. $mysqli->error);
}
$mysqli->set_charset (' UTF8 ');
Export_csv ();
function Export_csv () {
$filename = Date (' Ymdhis '). ". csv";//File name
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);//page encoding is used for utf-8, otherwise the exported Chinese is garbled
}
function array_to_string ($result) {
if (empty ($result)) {
return I ("No data to meet your requirements!") ");
}
Table header
$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;
}
PHP CSV Export