3

我试图在 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;

这不会返回确切的长度(它小于实际长度)。请指教。

4

5 回答 5

13

你告诉用户代理期待 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;
于 2010-08-25T07:29:19.727 回答
2

strlen返回正确答案:

echo strlen("1\n2\t3");

// prints 5

您将需要更仔细地检查您的输入。

于 2010-08-24T23:01:30.137 回答
2

content-length 标头不包括标头的长度加上响应的正文。

Content-Length: 响应正文的长度,以八位字节为单位(8 位字节)

仅供参考,因为“答案”中使用的变量是标题+数据。不要被误导。

于 2012-02-13T21:17:23.000 回答
1

在获取字符串长度之前,如果确实有错误(我还没有检查过) ,请从with或 with 其他类似函数中删除'\t''\n'符号。$datastr_replacestrlen()

于 2010-08-24T22:50:05.873 回答
1

您同时回显$header$data,但仅设置Content-Length为 的大小$data

如果$header包含额外的 HTTP 标头,您应该$header使用header(). 否则,您应该设置Content-Lengthstrlen($header."\n".$data).

于 2012-07-26T13:43:07.190 回答