我们已经设法将 mysql 表中的数据导出到 .txt 文件中。现在用写字板查看的问题很好。但是使用记事本甚至 microsoft word 看起来很糟糕,\n 无法正常工作,因为在记事本中,同一行上的所有内容都不尊重 \n。我应该添加什么?下面是我们的代码。
<?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
}