0

我们已经设法将 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     
} 
4

1 回答 1

3

记事本只读取 DOS 换行符\r\n(回车 + 换行)。如果不包含\r,则所有文本都将显示在一行上,可能会显示不正确的块字符。

我的建议是使用更好的文本编辑器来阅读它们,能够处理不同类型的换行符,而不是修改你的代码。对于 Windows ,我会推荐 Notepad++。软件世界中相当多的文件将使用\nUnix 风格的换行符进行编码,而记事本无法正确读取其中的任何一个(除了无法可靠地打开大文件之外,还有其他问题)。最好切换编辑器。

于 2012-05-17T13:11:46.810 回答