[英]Empty rows in csv file
I need a little help, I exporting table to csv file, and this added me a 8 empty rows. 我需要一点帮助,我将表导出到csv文件,这为我添加了8个空行。 Why ? 为什么呢 Maybe anybody can help me a little bit. 也许有人可以帮助我一点。
export.ctp file export.ctp文件
<?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. 但是我不希望这些空行,当我将此文件导入mysql时,它也添加了这些空行。
Thanks for helping ! 感谢您的帮助!
If I type var dump, then I get this. 如果我输入var dump,那么我得到了。
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. 将'./file1.csv'
替换为您的文件名和路径。 If you need to dump the CSV content on screen then replace the first line with $fh = STDOUT;
如果需要在屏幕上转储CSV内容,则将第一行替换为$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 "...";
<?php ?>
块之外的所有内容都是无声的,相当于echo "...";
So, these linefeeds are printed like echo "\\n\\n\\n\\n";
因此,这些换行符的打印方式类似于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";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.