This article mainly introduces the PHP implementation from the database exported to the. csv file method of the relevant information, the need for friends can refer to the following
PHP implementation export from database to. csv file method
Implementation code:
Public Function Export () {//Get data from the database, in order to save memory, do not read the data one time to memory, the subordinate handle in a row to read//output Excel file header, you can change the user.csv to the file name header (' Content-type:application/vnd.ms-excel '); Header (' content-disposition:attachment;filename= ' order.csv "'); Header (' cache-control:max-age=0 '); $where =array ("Paid" =>1, "Pay_type" =>array ("NEQ", "Offline"), "status" =>array ("LT", 3),); $stmt = M ("Group_order")->field ("Order_id,order_name,num,price,total_money,contact_name,phone,zipcode,adress, Wx_cheap,balance_pay,payment_money,tuan_type,pay_time,pay_type,third_id,is_mobile_pay,paid,status ")->where ( $where)->order ("order_id DESC")->limit (+)->select (); Open the PHP file handle, php://output indicates the direct output to the browser $fp = fopen (' php://output ', ' a '); Output Excel column name information $head = Array ("Order number", "Order name", "Purchase Quantity", "Unit Price", "Total Price", "Contact name", "Contact phone", "Postal Code", "Detailed address", "preferential amount", "Balance payment amount", "Real payment amount", " Type of sale (2 in kind) "," Payment Time "," Payment type "," third party payment ID "," whether the phone is paid "," whether payment "," Order Status "); foreach ($head as $i = + $v) {//CSV Excel supports GBK encoding, be sure to convert otherwise garbled $head [$i] = iconv (' utf-8 ', ' GBK ', $v);}Writes data through Fputcsv to the file handle Fputcsv ($FP, $head); Counter $cnt = 0; Every $limit line, refresh the output buffer, not too big, not too small $limit = 500; Data is fetched row by line without wasting memory $count = count ($stmt); for ($t =0; $t < $count; $t + +) {$cnt + +, if ($limit = = $cnt) {//Refresh output buffer to prevent problems caused by too much data ob_flush (); Flush (); $cnt = 0; } $row = $stmt [$t];foreach ($row as $i + = $v) {if ($i = = ' Pay_time ') {$v =date ("Y-m-d,h:i:s", $v); } $row [$i] = iconv (' utf-8 ', ' GBK ', $v); } fputcsv ($fp, $row); } fclose ($FP); }