Dolly
Dolly

Reputation: 1052

csv contains HTML while exporting that file in cakephp

I am trying to perform functions exporting and importing CSV file. I have done importing file successfully, but while exporting file, the downloaded CSV file contains HTML code with header, body and footer. I think that was from default.ctp, not sure.

Why, and from where, is that code automatically embedded ?

<?php function export()
    {
            $fp = NULL;
            $results = NULL;
            $row = NULL;        
            $results = $this->Order->find('all',array('fields'=> array('Order.sku','Order.inventory')));
            $fp = fopen('php://output','w+');
            $filename = "results.csv"; 
            header('Content-type: application/csv');
            header('Content-Disposition: attachment;');
            fputcsv($fp,array(
            'sku',
            'inventory'
            ));
            $ctr = count($results);
            print($ctr);
            foreach($results as $row) 
            {
                fputcsv($fp,array(
                $row['Order']['sku'],
                $row['Order']['inventory']
                ));
            }
          fclose($fp);

    } ?>

Upvotes: 0

Views: 1043

Answers (3)

Kiran
Kiran

Reputation: 921

Disable layout in controller

<?php

$this->layout=null;

?>

Upvotes: 0

Barry Chapman
Barry Chapman

Reputation: 6780

Thats a simple solution, either create a CSV layout that contains the necessary headers, or just use the built in ajax layout:

$this->layout = 'ajax';

In your controller action. That should fix it for you.

Upvotes: 1

Dunhamzzz
Dunhamzzz

Reputation: 14798

You need to disable layout rendering, stick this in your controller action:

$this->autoRender = false;

Tehnichally, this is not the correct way to do CSV, you should create a CSV layout and view, but if it works, ce le vie.

Upvotes: 1

Related Questions