[英]PHP export to CSV file has first two rows empty
我在數組中有以下數據,並想寫入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));
}
}
}
請使用框架的index.php之類的任何文件,或任何其他開頭帶有空行的文件,這可能會導致csv中的空行。
請檢查函數調用之前包含的其他文件,這些文件是否具有打印空間等。您可以使用記事本檢查是否在記事本中打開了導出的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));
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.