Exporting my database to CSV with PHP

Asked

Viewed 280 times

2

I created a php code that performs a twitter search and saves the result (100 tweets) in a database. In this code, I also have the option to select all tweets from the database and export them to a csv file.

However, if the tweet has a line break it will stay that way in csv: inserir a descrição da imagem aqui What do I do to save this tweet in just one line of csv (delete line break )

This is my code that exports tweets to 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; 
  • I made one with PDO that had no problem with line breaking, see if it helps you. https://gist.github.com/rafa-acioly/0718d3a5d5b377108052

  • 1

    I just want to remind you that the mysql_* is being discontinued for security reasons. I recommend using mysqli_* or PDO.

1 answer

3

I managed to solve by adding these 3 lines

$acentua = utf8_decode($row["$i"]);    <- meu código

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

$output .='"'.$acentua.'",';            <- meu código

Browser other questions tagged

You are not signed in. Login or sign up in order to post.