A web developer's blog. PHP, MySQL, CakePHP, Zend Framework, Wordpress, Code Igniter, Django, Python, CSS, Javascript, jQuery, Knockout.js, and other web development topics.

CakePHP 2.x: CSV File download from a database query

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.

Sources: A, B

This entry was posted in Uncategorized and tagged , , . Bookmark the permalink.

3 Responses to CakePHP 2.x: CSV File download from a database query

  1. Lance Campos says:

    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.

  2. Pingback: Setting up File Uploader / FineUploader Basic with CakePHP | Ekini … « CakePHP Articles

  3. paka says:

    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

Leave a Reply to Lance Campos Cancel reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>