[英]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.