【发布时间】:2015-10-27 02:37:16
【问题描述】:
我在一个数组中有以下数据,并想写入 CSV 文件。一切正常,除了我在 .csv 文件中看到前两个空行
感谢任何帮助...再次感谢!!!!
CSV 文件中的输出如下所示
空 Line1
空 Line2
ip 地址 ip 状态描述 hostmane mac owner 设备备注
数据……
数组数据:
Array (
[0] =>Array ( [ip address] => 1.3.2.1 [ip state] => Active [description] => [hostname] => [mac] => [owner] => [device] => [note] => )
[1] =>Array ( [ip address] => 1.3.2.2 [ip state] => Reserved [description] => [hostname] => linux [mac] => [owner] => test [device] => Linux Server [note] => Linux123 )
[2] => Array ( [ip address] => 1.3.2.3 [ip state] => Active [description] => [hostname] => [mac] => [owner] => [device] => [note] => )
[3] => Array ( [ip address] => 1.3.2.4 [ip state] => Active [description] => [hostname] => [mac] => [owner] => [device] => [note] => )
)
我用来写入 CSV 文件的 PHP 函数是:
switch("export-to-csv")
{
case "export-to-csv" :
// Submission from
$filename = $_GET["exformat"] . ".csv";
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=\"$filename\"");
header("Expires: 0");
ExportCSVFile($data);
//$_GET["exformat"] = '';
exit();
default :
die("Unknown action : ".$_POST["action"]);
break;
}
function ExportCSVFile($records) {
// create a file pointer connected to the output stream
#print_r ($records); return;
$fh = fopen( 'php://output', 'w' );
$heading = false;
if(!empty($records)) {
foreach($records as $row) {
if(!$heading) {
// output the column headings
fputcsv($fh, array_keys($row));
$heading = true;
}
// loop over the rows, outputting them
fputcsv($fh, array_values($row));
}
}
}
【问题讨论】:
-
您也可以在
if(!$heading)之后添加一个 else 条件来检查空字符串 ('')。我建议修剪字符串以捕获只有空格的条目。 -
感谢 devlin 的快速回复。我在 if(!$heading) $row = trim(preg_replace('/\s+/', ' ', $row)); 之前尝试使用此行但没有帮助。
-
任何人都知道如何避免 .csv 文件下的前两个空行...
-
尝试添加 ob_clean();在 fputcsv 之前。希望这会有所帮助。
标签: php