为什么我的Content-Length标题是错误的?

我试图找出在PHP 5.2中使用strlen()的确切长度的string。 string($ 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; 

确保你没有添加单引号和换行符。 string周围的单引号将评估\ n反斜杠和n,而不是换行符。

另外,确保你的string中没有特殊的字符,比如变音符号,因为那么strlen('ü')确实是2,因为它们是多字节的。 尝试strlen(utf8_decode('ü'));

另一种方法是使用mb_strlen()来代替。 正确设置mb_internal_encoding()

strlen返回正确的答案:

 echo strlen("1\n2\t3"); // prints 5 

您需要更仔细地检查您的input。

在获取string的长度之前,如果strlen()真的有bug(我没有检查过),用str_replace或者其他函数从$data删除'\t''\n'符号。

您同时回显$ header和$ data,但您只将Content-Length设置为$ data的大小。 如果$ header包含额外的HTTP头文件,则应使用header()输出$头文件。 否则,您应该将Content-Length设置为strlen($ header。“\ n”。$ data)。

内容长度标题不包括标题的长度加上响应的正文。

Content-Length:响应主体的长度,以八比特组为单位(8比特字节)

因为在“答案”中使用的variables是头+数据,所以只是供参考。 不要被误导。