Почему мой заголовок Content-Length неправильный? - PullRequest
2 голосов
/ 25 августа 2010

Я пытаюсь узнать точную длину строки, используя strlen () в php 5.2. Строка ($ 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;

Это не возвращает точную длину (это меньше, чем фактическая длина). Пожалуйста, совет.

Ответы [ 5 ]

13 голосов
/ 25 августа 2010

Вы говорите агенту пользователя ожидать 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;
2 голосов
/ 25 августа 2010

strlen возвращает правильный ответ:

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

// prints 5

Вам нужно будет более внимательно изучить ваши данные.

1 голос
/ 26 июля 2012

Вы выводите как $header, так и $data, но вы устанавливаете Content-Length для размера $data.

Если $header содержит дополнительные HTTP-заголовки, вы должны вывести $header используя header().В противном случае вы должны установить Content-Length на strlen($header."\n".$data).

1 голос
/ 14 февраля 2012

Заголовок content-length НЕ включает длину заголовков плюс тело ответа.

Content-Length: Длина тела ответа в октетах(8-битные байты)

Только к сведению, поскольку переменные, используемые в «ответе», представляют собой заголовок + данные.Не обманывайтесь.

1 голос
/ 25 августа 2010

Прежде чем получить длину строки, удалите символы '\t' и '\n' из $data с помощью str_replace или с другой подобной функцией, если strlen() действительно имеет ошибку (я не проверял это). *

...