[英]Why is my Content-Length header wrong?
我試圖在php 5.2中使用strlen()找出字符串的確切長度。 字符串($ data)包含'\\ t'和'\\ n'。
echo strlen($data);
碼:
// fetch table header
$header = '';
while ($fieldData = $result->fetch_field()) {
$header .= $fieldData->name . "\t";
}
// fetch data each row, store on tabular row data
while ($row = $result->fetch_assoc()) {
$line = '';
foreach($row as $value){
if(!isset($value) || $value == ""){
$value = "\t";
}else{
// important to escape any quotes to preserve them in the data.
$value = str_replace('"', '""', $value);
// needed to encapsulate data in quotes because some data might be multi line.
// the good news is that numbers remain numbers in Excel even though quoted.
$value = '"' . $value . '"' . "\t";
}
$line .= $value;
}
$data .= trim($line)."\n";
}
// this line is needed because returns embedded in the data have "\r"
// and this looks like a "box character" in Excel
$data = str_replace("\r", "", $data);
// Nice to let someone know that the search came up empty.
// Otherwise only the column name headers will be output to Excel.
if ($data == "") {
$data = "\nno matching records found\n";
}
// create table header showing to download a xls (excel) file
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=$export_filename");
header("Cache-Control: public");
header("Content-length: " . strlen($data); // tells file size
header("Pragma: no-cache");
header("Expires: 0");
// output data
echo $header."\n".$data;
這不會返回確切的長度(小於實際長度)。 請指教。
您告訴用戶代理期望strlen($ data),然后實際發送$ header。“\\ n”。$ data! 在代碼的最后嘗試這樣的東西......
$output=$header."\n".$data;
// create table header showing to download a xls (excel) file
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=$export_filename");
header("Cache-Control: public");
header("Content-length: " . strlen($output); // tells file size
header("Pragma: no-cache");
header("Expires: 0");
// output data
echo $output;
您同時回顯$header
和$data
,但您只將Content-Length
設置為$data
的大小。
如果$header
包含其他HTTP標頭,則應使用header()
輸出$header
。 否則,您應將Content-Length
設置為strlen($header."\\n".$data)
。
在獲取字符串長度之前,使用str_replace
或其他函數從$data
刪除'\\t'
和'\\n'
符號,如果strlen()
確實有bug(我沒有檢查過)。
內容長度標題不包括標題的長度加上響應的主體。
Content-Length:響應主體的長度,以八位字節為單位(8位字節)
僅供參考,因為“答案”中使用的變量是標題+數據。 不要被誤導。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.