Export large data to CSV via PHP

Exporting large data may cause Memory problems or timeout problems, here is how to avoid these problems.

$query = $this->db->query("select * from students where (DATE(order_date) between '$start' and '$end') ");
                $filename = "reports.csv";
                header('Content-type: application/csv');
                header('Content-Disposition: attachment; filename='.$filename);
                

                $fp = fopen('php://output', 'w');
                $fields = $query->list_fields();
                foreach($fields as $field){
                        $header[] = $field;
                }	
                fputcsv($fp, $header);
                
                foreach ($query->result_array() as $data) {
                        //$fp = fopen('php://output', 'a');
                        fputcsv($fp, $data);
                        
                 }
                fclose($fp);
                exit;
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s