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.
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: