1. Database out of data, stored in a two-dimensional array
$conn=NewMysqli (' localhost ', ' root ', ' root ', ' mydbpdo '); $result=$conn->query (' SELECT * from emp ')); $emps=Array(); while($row=$result-Fetch_assoc ()) { Static $i=0; $emps[$i] =$row; $i++; }
2. Output CSV data (header and content)
//set up memory consumptionSet_time_limit(0); Ini_set(' Memory_limit ', ' 512M '); //open a file handle for the Fputcsv () function$output=fopen(' Php://output ', ' W ') or die("Can ' t open php://output"); //tell the browser that this is a CSV file$filename= "Employee Information table".Date(' y-m-d ', Time()); Header("Content-type:application/csv"); Header("Content-disposition:attachment; Filename=$filename. csv "); //Output Table Header$table _head=Array(' id ', ' name ', ' age ', ' salary '); Fputcsv ($output,$table _head); //output each row of data to a fileforeach($emps as $e) { //unset ($e [' xx ']);//If there are extra fields you can use unset to remove//$e [' xx '] = isset ($e [' xxx '])? "XX": ' X '; Can do the corresponding processing//output content as requiredFputcsv ($output,array_values($e));
oB_flush ();
Flush ();
}
3. Closing the handle
fclose ($output); unset ($emps); Ob_flush (); Flush (); Exit ();
where Iconv (' utf-8 ', ' GBK ', $a), if necessary, can be used for transcoding when traversing
PHP Export CSV Table file