I am making the app by CakePHP 1.3 with MSSQL Server 2012. I successfully made the export CSV file from database.
At the first time, I made it having no problems. I continue to make some other function in my app. And than I try to test export function again.
And the problem occurred. The problem is in my CSV file, it has a lot empty rows appeared. I checked in my database, it has no null values and in my controller and export.ctp too.
I don't know why the problem was happened so can someone realize my false?
My Controller:
function csv_export() {
$this->set('title_for_layout','Export Words List');
Configure::write('debug',0);
$this->layout=false;
$filename = 'Wordlist_'.date('YmdHis');
$th=array('id','avoidance_word','avoidance_word_yomi','replace_word','replace_word_yomi','creator','create_time','updator','update_time','invalid_flg');
$Th_name=array('ID','Avoidance Words','Avoidance Words Yomi','Replace Word','Replace Word Yomi','Creator','Create Time','Updator','Update Time','Invalid Flag');
$td=$this->MAvoidanceWord->find('all', array('fields'=>$th));
$this->set(compact('filename','Th_name','td'));
}
My View:
<?php
$csv->addRow($Th_name);
foreach ($td as $t){
$csv->addRow();
$csv->addField($t['MAvoidanceWord']['id']);
$csv->addField($t['MAvoidanceWord']['avoidance_word']);
$csv->addField($t['MAvoidanceWord']['avoidance_word_yomi']);
$csv->addField($t['MAvoidanceWord']['replace_word']);
$csv->addField($t['MAvoidanceWord']['replace_word_yomi']);
$csv->addField($t['MAvoidanceWord']['creator']);
$csv->addField($t['MAvoidanceWord']['create_time']);
$csv->addField($t['MAvoidanceWord']['updator']);
$csv->addField($t['MAvoidanceWord']['update_time']);
$csv->addField($t['MAvoidanceWord']['invalid_flg']);
$csv->endRow();}
$csv->setFilename($filename);
echo $csv->render(true,'UTF-8');
?>
And my CSV file:
Update: My CSV file open with Notepad++
Remove addRow
from inside the foreach:
foreach ($td as $t){
// $csv->addRow();
$csv->addField($t['MAvoidanceWord']['id']);
...
You can either use addRow(array)
or addField
(several times) and endRowThe fact that you have
addRow` right now means it is adding a blank line several times.
Second way: Try adding ob_clean();
before $csv->addRow($Th_name);
May be issue is not in this code.
Check twice, that you have not any linefeeds echoing anywhere.
May be anything like:
<?php
//php code
?>
↓
↓
↓
All content outside your <?php ?>
block is silent equivalent of echo "...";
So, these linefeeds are printed like echo " ";
Good practice is to remove last ?>
at all