Here is a quick way to output/stream/download a CSV file from your database using CakePHP.
For simplicity, I have placed everything in the controller. Not good practice but it quickly does the job.
<?php class UsersController extends AppController { // ...snip... // the rest of your code here public function downloadentries() { if($this->request->is('post')) { $this->loadModel('Member'); $filename = "myfile.csv"; $start_date = '2012-10-08 00:00:00'; $end_date = '2012-10-08 23:59:59'; $results = $this->Member->find('all', array( 'conditions' => array('Member.created >=' => $start_date, 'Member.created <=' => $end_date) )); $csv_file = fopen('php://output', 'w'); header('Content-type: application/csv'); header('Content-Disposition: attachment; filename="'.$filename.'"'); $header_row = array("id", "name", "email"); fputcsv($csv_file,$header_row,',','"'); foreach($results AS $result) { $row = array( $result['Member']['id'], $result['Member']['name'], $result['Member']['email'] ); fputcsv($csv_file,$row,',','"'); } fclose($csv_file); } $this->layout = false; $this->render(false); return false; } // ... more code here... } |
You might be also interested in outputting it as an Excel File: Zend Framework: View File downloaded as Excel File. Different framework but the same idea.
CakePHP is a fast development structure for PHP that provides an extensible structure for creating, keeping, and implementing programs. Using generally known style like MVC and ORMwithin the meeting over settings paradigm.
Pingback: Setting up File Uploader / FineUploader Basic with CakePHP | Ekini … « CakePHP Articles
I want to use encoding utf-8, but i tried to use
header(“Content-Type: application/vnd.ms-excel; charset=UTF-8″);
-it works not correct font. Please help me check