+6 votes
2k views
in Programming by Expert (5.1k points)
How to generate CSV file in cake php?
by (990 points)
hello amit sir , could you please tell me the what is the problem in code below ,I also want the same thing in php .

2 Answers

–1 vote
by
edited by

It's actually really easy, you'll need to create a view that will just loop the content, and write it out, and change the header so that it will download a file with a csv file.

Here's the code 

  1. // Let's say example is id, name, surname, gender
  2. // Controller - ExamplesController.php
  3. class ExamplesController extends AppController
  4. {
  5.     /**
  6.      * csv method
  7.      *
  8.      * @return void
  9.      */
  10.     public function csv()
  11.     {
  12.         $this->layout = 'csv';
  13.         $this->set('examples', $this->Example->find("all"));
  14.     }
  15. }
  16. // Layout - csv.ctp
  17. //generate csv header  
  18. header("Content-type: application/octet-stream");  
  19. header("Content-Disposition: attachment; filename=export.csv");  
  20. header("Pragma: no-cache");  
  21. header("Expires: 0");  
  22. echo $this->fetch('content');
  23. // View - csv.ctp
  24. foreach ($examples as $example) {
  25.     echo implode(",",$example["Example"]);
  26. }
 
// Let's say example is id, name, surname, gender
// Controller - ExamplesController.php
 
class ExamplesController extends AppController
{
 
    /**
     * csv method
     *
     * @return void
     */
    public function csv()
    {
        $this->layout = 'csv';
        $this->set('examples', $this->Example->find("all"));
    }
}
 
// Layout - csv.ctp
 
//generate csv header  
header("Content-type: application/octet-stream");  
header("Content-Disposition: attachment; filename=export.csv");  
header("Pragma: no-cache");  
header("Expires: 0");  
 
echo $this->fetch('content');
 
// View - csv.ctp
 
foreach ($examples as $example) {
    echo implode(",",$example["Example"]);
}
by (990 points)
edited by
@Lucas sir, Could you please update your answer and provide the solution because i also want the same thing in php, I hope you will help me out. Thanks !
0 votes
by (590 points)
firstly you need a helper which generate the CSV file!..
by (1.4k points)
which kind of helper could you explain ?

Not a Member yet?

Ask to Folks Login

My Account

Your feedback is highly appreciated