使用php将我的数据库导出到csv

时间:2015-08-27 20:10:28

标签: php mysql csv

我在php中创建了一个代码,在twitter上执行搜索并将结果(100条推文)保存在数据库中。在此代码中,我还可以选择所有数据库推文并将它们导出到csv文件。

但是,如果推文有换行符,他会在csv中那样:

enter image description here

如何将此推文保存在csv的一行(删除换行符)

这是我将推文导出到csv的代码:

// Database Connection

$host="xxxxxx";
$uname="xxxxx";
$pass="xxxxxx";
$database = "xxxxxx";   

$connection=mysql_connect($host,$uname,$pass); 

echo mysql_error();

//or die("Database Connection Failed");
$selectdb=mysql_select_db($database) or die("Database could not be selected");  
$result=mysql_select_db($database)
or die("database cannot be selected <br>");


// Fetch Record from Database

$output         = "";
$table          = "tabela_tweets_novo"; // Enter Your Table Name
$sql            = mysql_query("select tweet from $table");
$columns_total  = mysql_num_fields($sql);

// Get The Field Name

for ($i = 0; $i < $columns_total; $i++) {
    $heading    =   mysql_field_name($sql, $i);
    $output     .= '"'.$heading.'",';
}
$output .="\n";

// Get Records from the table

while ($row = mysql_fetch_array($sql)) {
for ($i = 0; $i < $columns_total; $i++) {

$acentua = utf8_decode($row["$i"]);
$output .='"'.$acentua.'",';
}
$output .="\n";
}

// Download the file

$filename =  "UUXPost.csv";
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename='.$filename);

echo $output;
exit;

1 个答案:

答案 0 :(得分:1)

在代码中插入3行并将替换字符串更改为您想要的

$acentua = utf8_decode($row["$i"]);    <- your code

$order   = array("\r\n", "\n", "\r");
$replace = '<br />';
$acentua = str_replace($order, $replace, $acentua);

$output .='"'.$acentua.'",';            <- your code