我在数组中有以下数据,并希望写入CSV文件。除了我在.csv文件中看到的前两个空行之外,一切都正常
任何帮助我们都很感激。再次感谢!
CSV文件中的输出看起来像空的Line1
empty Line2 ip address ip state description hostmane mac owner device notes data......数组数据:
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));
}
}
}发布于 2015-10-27 12:21:55
请任何文件,如框架的index.php或任何其他文件在开头有空行,这可能会导致csv中的空行。
发布于 2015-10-27 13:29:00
请检查你的其他文件,这是包括在函数调用,并有打印空间等。你可以检查,使用记事本,打开输出的csv文件在记事本,你可以看到是否有空间,你的php代码是完美的,没有任何问题。我已经用波纹数组测试过了,它工作得很好。
$data = array(
'0' => array('ip address' => '1.3.2.1', 'ip state' => 'Active'),
'1' => array('ip address' => '1.3.2.2', 'ip state' => 'Reserved'),
'2' => array('ip address' => '1.3.2.3', 'ip state' => 'Active'),
'3' => array('ip address' => '1.3.2.4', 'ip state' => 'Active')
);
switch ("export-to-csv")
{
case "export-to-csv" :
$filename = "1.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);
exit();
default :
die("Unknown action : " . $_POST["action"]);
break;
}
function ExportCSVFile($records)
{
$fh = fopen('php://output', 'w');
$heading = false;
if (!empty($records))
{
foreach ($records as $row)
{
if (!$heading)
{
fputcsv($fh, array_keys($row));
$heading = true;
}
fputcsv($fh, array_values($row));
}
}
}https://stackoverflow.com/questions/33359067
复制相似问题