We have manage to export data from our mysql table into a .txt file. The problem now when view it with wordpad is nice. But with notepad or even microsoft word it looks bad the \n is not working well as in notepad all of it on same line did not respect the \n. What should I add? Below is our codes.
<?php
require_once('config.php');
// If the checkbox values are meant to all be integers, you might want to perform some validation/sanitisation/filtering here
// Up to you to do that // Collapse the IDs from the checkboxes into a comma-delimited string
$link = mysql_connect(dbHost, dbUser, dbPassword);
if(!$link)
{
die('Failed to connect to server: ' . mysql_error());
}
//Select database
$db = mysql_select_db(dbDatabase);
if(!$db)
{
die("Unable to select database");
}
// Template the SQL Query
$sqlStr = 'SELECT stringData,dataInsertDateTime FROM tblData WHERE aID=1965';
// Compile the SQL Query String
//$sqlStr = sprintf( $sqlTpl , $export_ids );
// Execute the SQL Query
if( !( $sqlRes = mysql_query( $sqlStr ) ) )
{
// SQL Error - Log it, Handle it
}
elseif( mysql_num_rows( $sqlRes )==0)
{ // No Rows Returned - Log it, Handle it
}
else
{ // We have results - process them
$text = array();
while( $r = mysql_fetch_assoc( $sqlRes ) )
{ // Looping through the returned rows, adding them to the $text array
$text[] = $r['stringData']." ".$r['dataInsertDateTime'];
}
// Collapse the $text array down into a normal string, with one element per line
$output = implode( "\n" , $text );
// Output Handling from @narcisradu's answer
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false);
header("Content-Transfer-Encoding: binary;\n");
header("Content-Disposition: attachment;filename=\"filename.txt\";\n");
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Description: File Transfer");
header("Content-Length: ".strlen($output).";\n");
echo $output; die; // Prevent any further output
}
Notepad only reads DOS linebreaks which are
\r\n(carriage return + newline). If you don’t include the\r, all your text will all appear on one line, possibly with incorrectly displayed block characters.My advice is to use a better text editor to read them, capable of handling different types of linebreaks, rather than modify your code. For Windows I would recommend Notepad++. Quite a lot of files in the software world are going to be encoded with
\nUnix-style linebreaks, and Notepad is incapable of reading any of them properly (In addition to being unable to reliably open large files, among other problems). Best to switch editors.