1

I want to do an ASCII text download of user-selected SQL data, that can be opened immediately in notepad. DB connection works fine, as do "header" commands to initiate download, but I'll be damned if I can get the end-of-line characters to show up properly.

The header is statically defined via:

$header = <<<EOD
  #Some header information
  #goes here on multiple
  #lines
  EOD;

with each row data being concatenated with tabs:

$RS_SQL = $DBinterface->dbGetRecordSet($someQuery);
foreach($RS_SQL as $row) {
  $rowdata = '';
  foreach($row as $key=>$val) {
    if((!(int)$key) && $key!='0') {
      $rowdata[] = $row[$key];
    }
  }
  $dataOutput.=implode("\t",$rowdata)."\n";
}
header("Content-type: text/plain; charset=ISO-8859-1");
header("Content-Disposition: attachment; filename=SQLDataExport.txt");
echo $header."\n".$dataOutput;

Header shows up in notepad fine, and all the tab spacing is exactly as designed... However, any attempt to format rows nicely via \r or \n characters result in a single line with unknown characters (square boxes) where the linefeeds should be.

I've tried writing the file to the server, then reading the stream and outputting; tried variations on the header information... Kinda get the idea that there's something odd with the way the page is being downloaded to the browser via binary, but?

What am I missing?

Many thanks.

Pythonist
  • 33
  • 1
  • 8
  • Not related to your square box issue, but notepad will need `\r\n` instead of just `\n` else it will ignore the newline. – Joe Bowman Jun 08 '12 at 12:25

2 Answers2

0

Try adding it in the header as UTF-8:

header("Content-type: text/plain; charset=utf-8");

Hope it helps! :) If not, check your PHP code for any UTF-8 BOM!

Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
0

Instead of using "\n" or "\r\n", use PHP_EOL for this. It handles any cross platform issues and is good for writing files that are meant to be saved on the server or client.

This question has some information and could be considered related to what you are trying to do.

You would use it like so:

$RS_SQL = $DBinterface->dbGetRecordSet($someQuery);
foreach($RS_SQL as $row) {
  $rowdata = '';
  foreach($row as $key=>$val) {
    if((!(int)$key) && $key!='0') {
      $rowdata[] = $row[$key];
    }
  }
  $dataOutput.=implode("\t",$rowdata).PHP_EOL;
}
header("Content-type: text/plain; charset=ISO-8859-1");
header("Content-Disposition: attachment; filename=SQLDataExport.txt");
echo $header."\n".$dataOutput;
Community
  • 1
  • 1
Buggabill
  • 13,726
  • 4
  • 42
  • 47
  • Thank you - that works nicely. I will trade all my end-lines to that constant. Interestingly, though, this is not a cross-platform issue... IIS on Windows Server talking to windows notepad via IE. – Pythonist Jun 08 '12 at 12:35
  • Very good. Feel free to accept the answer so that others know that this worked for you! – Buggabill Jun 08 '12 at 12:36