cakephp中实现csv文件导出

cakephp实现csv导出的方法并不复杂,可以通过引入一个CSVhelper的方法来实现,cakephp版本1.x或2.x都支持,但要注意不同版本的命名规则。

1.保存下面的代码为CsvHelper.php(如果是cakephp1.x版本,名字改为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.添加这个Helper到controller中,假设是/app/Controller/PostsController

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

3.在此controller中添加导出方法

function download()
{
    $this->set('posts', $this->Post->find('all'));
    $this->layout = null;
    $this->autoLayout = false;
    Configure::write(‘debug’, ’0′);
}

4.在模版中添加上面导出操作的链接,地址/app/view/Posts/index.ctp

 echo $this->Html->link('CSV导出',array('controller'=>'posts','action'=>'download'), array('target'=>'_blank'));

5.最后一步,新建/app/view/Posts/download.ctp

<?php
    //设置标题行
    $header_line= array('id','title');
    $this->Csv->addRow($header_line);
    //设置内容
    foreach ($posts as $post)
    {
        $line = $post['Post'];
        $this->Csv->addRow($line);
     }
    $filename='posts';
    //输出中文加GBK参数
     echo  $this->Csv->render($filename,'GBK');
?>
原文地址:https://www.cnblogs.com/mafeifan/p/3111295.html