Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>This solution is for CakePHP 2.0.. u can also integrate it in CakePHP 1.3</p> <p>Step 1: Save the following file as Csv.php into your app/View/Helper directory</p> <pre><code>&lt;?php class CsvHelper extends AppHelper { var $delimiter = ','; var $enclosure = '"'; var $filename = 'Export.csv'; var $line = array(); var $buffer; function CsvHelper() { $this-&gt;clear(); } function clear() { $this-&gt;line = array(); $this-&gt;buffer = fopen('php://temp/maxmemory:'. (5*1024*1024), 'r+'); } function addField($value) { $this-&gt;line[] = $value; } function endRow() { $this-&gt;addRow($this-&gt;line); $this-&gt;line = array(); } function addRow($row) { fputcsv($this-&gt;buffer, $row, $this-&gt;delimiter, $this-&gt;enclosure); } function renderHeaders() { header('Content-Type: text/csv'); header("Content-type:application/vnd.ms-excel"); header("Content-disposition:attachment;filename=".$this-&gt;filename); } function setFilename($filename) { $this-&gt;filename = $filename; if (strtolower(substr($this-&gt;filename, -4)) != '.csv') { $this-&gt;filename .= '.csv'; } } function render($outputHeaders = true, $to_encoding = null, $from_encoding ="auto") { if ($outputHeaders) { if (is_string($outputHeaders)) { $this-&gt;setFilename($outputHeaders); } $this-&gt;renderHeaders(); } rewind($this-&gt;buffer); $output = stream_get_contents($this-&gt;buffer); if ($to_encoding) { $output = mb_convert_encoding($output, $to_encoding, $from_encoding); } return $this-&gt;output($output); } } ?&gt; </code></pre> <p>Step 2: Add this Helper to your controller:</p> <pre><code>var $helpers = array('Html', 'Form','Csv'); </code></pre> <p>Step 3: create a method “download” at controller for eg. homes_controller.php</p> <pre><code>&lt;?php function download() { $this-&gt;set('orders', $this-&gt;Order-&gt;find('all')); $this-&gt;layout = null; $this-&gt;autoLayout = false; Configure::write('debug', '0'); } ?&gt; </code></pre> <p>Step 4: put this link on page from where you have to download CSV</p> <pre><code>&lt;?php echo $this-&gt;Html-&gt;link('Download',array('controller'=&gt;'homes','action'=&gt;'download'), array('target'=&gt;'_blank')); ?&gt; </code></pre> <p>Step: 5 (final step)</p> <p>Put this code on View/Homes/download.ctp</p> <pre><code>&lt;?php $line= $orders[0]['Order']; $this-&gt;CSV-&gt;addRow(array_keys($line)); foreach ($orders as $order) { $line = $order['Order']; $this-&gt;CSV-&gt;addRow($line); } $filename='orders'; echo $this-&gt;CSV-&gt;render($filename); ?&gt; </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload