未生成Csv

时间:2016-04-26 09:38:52

标签: csv cakephp

我在CakePHP工作。我想生成CSV文件。这里我在我的视图文件中编写了代码,代码是:

foreach($com as $v)
{
   $this->Csv->addRow($v);
}
$filename='PollAnswer';
echo $this->Csv->render($filename);

这里$ com写的数组像:

Array
(
  [0] => Basketball, Total Vote :- 4,Marcel 55-Sandra-Avishek-Dan Guiora
  [1] => Natacion, Total Vote :- 2,Madhumoy-Spanish Sun
  [2] => Rugby, Total Vote :- 1,Ramanuj
  [3] => Hockey, Total Vote :- 1,Victoria Ricciano
)

它给我空白的结果。那么,我该如何生成CSV?

注意:我正在使用CakePHP版本1.3.13

1 个答案:

答案 0 :(得分:0)

您可以将其集成到CakePHP 1.3中 步骤1:将以下文件作为Csv.php保存到您的app / View / Helper目录

<?php
class CsvHelper extends AppHelper
{
var $delimiter = ',';
var $enclosure = '"';
var $filename = 'Export.csv';
var $line = array();
var $buffer;

function CsvHelper()
{
    $this->clear();
}
function clear() 
{
    $this->line = array();
    $this->buffer = fopen('php://temp/maxmemory:'. (5*1024*1024), 'r+');
}

function addField($value) 
{
    $this->line[] = $value;
}

function endRow() 
{
    $this->addRow($this->line);
    $this->line = array();
}

function addRow($row) 
{
    fputcsv($this->buffer, $row, $this->delimiter, $this->enclosure);
}

function renderHeaders() 
{
    header('Content-Type: text/csv');
    header("Content-type:application/vnd.ms-excel");
    header("Content-disposition:attachment;filename=".$this->filename);
}

function setFilename($filename) 
{
    $this->filename = $filename;
    if (strtolower(substr($this->filename, -4)) != '.csv') 
    {
        $this->filename .= '.csv';
    }
}

function render($outputHeaders = true, $to_encoding = null, $from_encoding ="auto") 
{
    if ($outputHeaders) 
    {
        if (is_string($outputHeaders)) 
        {
            $this->setFilename($outputHeaders);
        }
        $this->renderHeaders();
    }
    rewind($this->buffer);
    $output = stream_get_contents($this->buffer);

    if ($to_encoding) 
    {
        $output = mb_convert_encoding($output, $to_encoding, $from_encoding);
    }
    return $this->output($output);
}
}
?>

步骤2:将此助手添加到控制器:

var $helpers = array('Html', 'Form','Csv'); 

步骤3:在控制器上创建一个方法“下载”,例如。 homes_controller.php

<?php
function download()
{
    $this->set('orders', $this->Order->find('all'));
    $this->layout = null;
    $this->autoLayout = false;
    Configure::write('debug', '0');
}
?>

第4步:将此链接放在您必须下载CSV

的页面上
<?php
echo $this->Html->link('Download',array('controller'=>'homes','action'=>'download'), array('target'=>'_blank'));
?>

步骤:5(最后一步) 将此代码放在View / Homes / download.ctp

<?php
 $line= $orders[0]['Order'];
 $this->CSV->addRow(array_keys($line));
 foreach ($orders as $order)
 {
      $line = $order['Order'];
       $this->CSV->addRow($line);
 }
 $filename='orders';
 echo  $this->CSV->render($filename);
?>

谢谢,快乐编码:)