简体   繁体   English

从PHP的CSV导出中删除空行

[英]Remove empty lines from CSV Export in PHP

I am using this Function I found here on stackoverflow 我正在使用我在stackoverflow上找到的此函数

How to create and download a csv file from php script? 如何从php脚本创建和下载csv文件?

function array_to_csv_download($array, $filename = "export.csv", $delimiter=";") {
    $f = fopen('php://output', 'w');

    foreach ($array as $line) {
        fputcsv($f, $line, $delimiter);
    }

    header('Content-Type: application/csv');
    header('Content-Disposition: attachement; filename="'.$filename.'";');
}   

The Problem is in the export file i have now 4 extra empty lines. 问题出在导出文件中,我现在有4个额外的空行。

How i can fix this function to prevent these extra lines. 我如何解决此功能,以防止出现这些多余的行。

Array ( 

[0] => Array ( [start] => 001-F15:B2:1-F [dest] => 002-F15:B2:5-Y [rres_1] => 100 [rres_2] => 100 [rres_3] => 100 [runit_1] => 0 [runit_2] => 0 [runit_3] => 0 [runit_4] => 0 [runit_5] => 0 [runit_6] => 0 [worker] => 0 [duration] => 12 ) 

[1] => Array ( [start] => 001-F15:B2:1-F [dest] => 005-F15:A5:3-M [rres_1] => 0 [rres_2] => 0 [rres_3] => 0 [runit_1] => 100 [runit_2] => 100 [runit_3] => 100 [runit_4] => 0 [runit_5] => 0 [runit_6] => 0 [worker] => 0 [duration] => 12 ) 

[2] => Array ( [start] => 006-F15:E4:2-Y [dest] => 004-F15:A5:1-Y [rres_1] => 0 [rres_2] => 0 [rres_3] => 0 [runit_1] => 0 [runit_2] => 0 [runit_3] => 0 [runit_4] => 100 [runit_5] => 100 [runit_6] => 100 [worker] => 100 [duration] => 12 ) 
) 

This lines are printed out in the export.csv correctly 此行正确打印在export.csv

now the complete code: 现在完整的代码:

function array_to_csv_download($array, $filename = "export.csv", $delimiter=";") {
    header('Content-Type: application/csv');
    header('Content-Disposition: attachement; filename="'.$filename.'";');

    // open the "output" stream
    // see http://www.php.net/manual/en/wrappers.php.php#refsect2-wrappers.php-unknown-unknown-unknown-descriptioq
    $f = fopen('php://output', 'w');

    foreach ($array as $line) {
        fputcsv($f, $line, $delimiter);
    }
}   
$sql='SELECT p1.planet_name AS start, p2.planet_name AS dest, rres_1, rres_2, rres_3, runit_1, runit_2, runit_3, runit_4, runit_5, runit_6, worker, duration FROM traderoute tr 
        INNER JOIN planets p1 ON p1.planet_id=tr.start_planet
        INNER JOIN planets p2 ON p2.planet_id=tr.dest_planet
        WHERE player_id='.$game->player['user_id'];
$export=$db->queryrowset($sql); 
array_to_csv_download($export);
die();

I needed to clean the lines after the closing PHP ?> tag in the included PHP files. 我需要在包含的PHP文件中的PHP ?>标记关闭后清除所有行。 Then the empty lines in the csv file were gone. 然后,csv文件中的空行消失了。

Try checking for a blank line like this: 尝试检查像这样的空行:

foreach ($array as $line) {
   if(trim($line)!="")
   {
      fputcsv($f, $line, $delimiter);
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM