PHP Export CSV Table file

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.