2016-04-26 18 views
0

私はCakePHPで作業しています。私はCSVファイルを生成したい。私の見解・ファイルとコードでここに私が書いたコードは以下のとおりです。ここで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

+0

この問題を解決するために私を助けて@arilia .. –

答えて

0

で働いているあなたはCakePHPの1.3 ステップ1にそれを統合することができます:あなたのアプリ/ビュー/ヘルパーディレクトリ

にCsv.phpとして、次のファイルを保存します
<?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:お使いのコントローラにこのヘルパーを追加する方法を作成する「downl oad "をコントローラーに入力します。 homes_controller.php

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

ステップ4:表示/ホームズ/ダウンロードにこのコードを入れて5(最終段階) :あなたは

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

ステップCSV

をダウンロードする必要がどこからページにこのリンクを置きます。 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); 
?> 

おかげで、ハッピーコーディング:)

関連する問題