![](/img/trans.png)
[英]PHP - cannot modify header information - headers already sent by (output started at
[英]During CSV downloading - Warning: Cannot modify header information - headers already sent by (output started at
以下小演示代碼已成功運行
<?php
$list = array
(
"ID,Name,Preview,Payout",
"Peter,Griffin,Oslo,Norway",
"Glenn,Quagmire,Oslo,Norway",
);
$today_doc=date("Y-m-d").".csv";
$file = fopen($today_doc,"w");
foreach ($list as $line)
{
fputcsv($file,explode(',',$line));
}
fclose($file);
// We'll be outputting a csv
header('Content-type: text/csv');
// It will be called contacts.csv
header('Content-Disposition: attachment; filename="'.$today_doc.'"');
// The PDF source is in original.csv
readfile($today_doc);?>
我在腳本中使用了上面的演示代碼,然后它不起作用。 說->警告:無法修改標頭信息-標頭已經發送過(輸出始於
$selected_ids=$_POST['selected_id'];
$xyz="";
$list = array
("ID,Offer Name,Emp,salary");
$i=0;
foreach($selected_ids as $id)
{
$xyz.=$id.',';
}
$xyz=trim($xyz,',');
$extract=mysqli_query($con,"SELECT * FROM `emp_record` WHERE id in ($xyz)") or die(mysqli_error($con));
while($row = mysqli_fetch_array($extract))
{
$i++;
$list[$i]=$row["id"].','.$row["name"].','.$row["emp"].','.$row["salary"];
}
$today_doc=date("Y-m-d").".csv";
$today_doc="contacts.csv";
$file = fopen($today_doc,"w");
foreach ($list as $line)
{
fputcsv($file,explode(',',$line));
}
fclose($file);
// We'll be outputting a csv
header('Content-type: text/csv');
// It will be called contacts.csv
header('Content-Disposition: attachment; filename=contacts.csv');
//The PDF source is in original.csv
readfile("contacts.csv");
}
任何人都可以幫助解決該問題。
將標頭函數放在任何回顯/輸出之前:
<?php
header('Content-type: text/csv');
header('Content-Disposition: attachment; filename=contacts.csv');
編輯:
哦,這不是您的問題,但是,如果您要這樣,您應該回顯此標題:“ header('Content-type:text / csv'); header('Content-Disposition:attachment; filename = contacts.csv'); “ 然后從文件中加載某些格式的csv,例如。 “ $ csv”,然后僅回顯內容,例如:
<?php
header('Content-type: text/csv');
header('Content-Disposition: attachment; filename=contacts.csv');
$csv = file_get_contents('YOUR PATH');
echo $csv;
exit;
在以下情況下,您將始終收到此錯誤“警告:無法修改標題信息-標題已發送”
您在之前留空行
如果該調用是ajax調用,並且您在調用標頭之前回顯了一些字符。
只是確保之前沒有字符
你可以加:
ob_start()
在開始時
和
ob_flush()
結尾
例:
<?php ob_start(); ?>
<?php
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=export.csv');
.......
ob_flush();
?>
注意
如果需要,可以使用:
ob_start("ob_gzhandler")
ob_gzhandler()旨在用作ob_start()的回調函數,以幫助促進將gz編碼的數據發送到支持壓縮網頁的Web瀏覽器。
你看:
和
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.