Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

export csv in zend framework

I'm trying to export a database table as a .csv downloadable from the browser. My code is zend framework based and I'm almost there with the following action:

public function exportTableAction()
{
    $this->_helper->layout->disableLayout();
    $this->_helper->viewRenderer->setNoRender();

    $fileName = $this->_getParam('fileName');
    $tableName = $this->_getParam('tableName');       

    header('Content-type: application/octet-stream');
    header('Content-Disposition: attachment; filename="'.$fileName.'"');

    echo $this->getCsv($tableName, $fileName);
}

I can download my .csv file containing valid data. However, even if I disabled the layout and the renderer, I still get the output of the header, sidebar, and footer of my page at the end of my .csv file. Is there a way to disable any html output other than the one generated in my exportTableAction? Or can I send the header information and the csv string to the browser in a different way?

BTW: I'm using the action stack plugin to help me render the header and sidebar as follows:

...
$actionStack = $front->getPlugin('Zend_Controller_Plugin_ActionStack');
$actionStack->pushStack($userlogAction);
$actionStack->pushStack($rightcolAction);

Cheers, Adrian

like image 720
aimfeld Avatar asked Jul 16 '09 08:07

aimfeld


3 Answers

We found a solution to the problem. I replaced the following line

$this->_helper->viewRenderer->setNoRender();

by

$this->_helper->viewRenderer->setNeverRender();

If setNeverRender() is used, no views are rendered (from plugin neither).

like image 122
aimfeld Avatar answered Nov 15 '22 09:11

aimfeld


You can use contextSwitch action helper.

public $contexts = array(
    'test'     => array('csv')
);

public function testAction()
{
    $filename = time() . '.csv';
    $this->_helper->contextSwitch()->addContext('csv',
            array('suffix' => 'csv',
                  'headers' => array('Content-Type' => 'application/csv',
                                     'Content-Disposition' => 'attachment; filename="'. $filename.'"')))->initContext('csv');
    ........................
    ........................
}
like image 29
Dmitro Avatar answered Nov 15 '22 09:11

Dmitro


$this->_helper->viewRenderer->setNoRender();
$this->view->layout()->disableLayout();

$response = $this->getResponse();
$response->setHeader('Content-type', 'application/octet-stream');
$response->setHeader('Content-Disposition', 'attachment; filename="contatos.csv"');

echo $your_csv_content;
like image 1
Diego Armando Avatar answered Nov 15 '22 08:11

Diego Armando