I need a little help, I exporting table to csv file, and this added me a 8 empty rows. Why ? Maybe anybody can help me a little bit.
export.ctp file
<?php
foreach ($data as $row):
foreach ($row['Kontaktid'] as &$cell):
// Escape double quotation marks
$cell = '"' . preg_replace('/"/','""',$cell) . '"';
endforeach;
echo implode(',', $row['Kontaktid']) . "\n";
endforeach;
?>
And this is doing this
But I dont want these empty rows, when I import this file to mysql, then its added these empty rows too.
Thanks for helping !
If I type var dump, then I get this.
Try this:
$fh = fopen('./file1.csv', 'wt');
foreach ($data as $row) {
if (! empty($row['Kontaktid'])) {
fputcsv($fh, $row['Kontaktid']);
}
}
fclose($fh);
Replace './file1.csv'
with your filename and path. If you need to dump the CSV content on screen then replace the first line with $fh = STDOUT;
Using you code:
<?php
foreach ($data as $row):
$isRowEmpty = false;
foreach ($row['Kontaktid'] as &$cell):
// we assume the row is empty if the first cell is empty
if(empty($cell)) {
$isRowEmpty = true;
break;
} else {
// Escape double quotation marks
$cell = '"' . preg_replace('/"/','""',$cell) . '"';
}
endforeach;
if(!$isRowEmpty) {
echo implode(',', $row['Kontaktid']) . "\n";
}
endforeach;
?>
Hope this helps!
Just check, your line not empty:
<?php
foreach ($data as $row):
if (!isset($row['Kontaktid']) || !$row['Kontaktid']) continue; // <-add this line
foreach ($row['Kontaktid'] as &$cell):
// Escape double quotation marks
$cell = '"' . preg_replace('/"/','""',$cell) . '"';
endforeach;
echo implode(',', $row['Kontaktid']) . "\n";
endforeach;
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 "\\n\\n\\n\\n";
Good practice is to remove last ?>
at all
add this:
if (isset($row['Kontaktid']) && strlen($row['Kontaktid']) && !empty($row['Kontaktid']))
before:
echo implode(',', $row['Kontaktid']) . "\n";
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.