Jump to content

[SOLVED] Export DB to CSV script help


tqla

Recommended Posts

This script works but it has one little snag: Carriage returns in text fields are forcing text on new lines into new fields on the CSV doc. Does anybody know why? Thanks.

<?php
$host = '';
$user = '';
$pass = '';
$db = '';
$table = '';
$file = 'export';

$link = mysql_connect($host, $user, $pass) or die("Can not connect." . mysql_error());
mysql_select_db($db) or die("Can not connect.");

$result = mysql_query("SHOW COLUMNS FROM ".$table."");
$i = 0;
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_assoc($result)) {
$csv_output .= $row['Field'].", ";
$i++;
}
}
$csv_output .= "\n";

$values = mysql_query("SELECT * FROM ".$table."");
while ($rowr = mysql_fetch_row($values)) {
for ($j=0;$j<$i;$j++) {
$csv_output .= $rowr[$j].", ";
}
$csv_output .= "\n";
}

$filename = $file."_".date("Y-m-d_H-i",time());
header("Content-type: application/vnd.ms-excel");
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header( "Content-disposition: filename=".$filename.".csv");
print $csv_output;
exit;
?>

Link to comment
https://forums.phpfreaks.com/topic/102940-solved-export-db-to-csv-script-help/
Share on other sites

You could try using PHP's fputcsv, instead of writing your own function.

 

http://us.php.net/fputcsv

 

 

Here is example from the comments the fputcsv page on how you can use fputcsv to format your data.

<?php
// output up to 5MB is kept in memory, if it becomes bigger it will automatically be written to a temporary file
$csv = fopen('php://temp/maxmemory:'. (5*1024*1024), 'r+');

fputcsv($csv, array('blah','blah'));

rewind($csv);

// put it all in a variable
$output = stream_get_contents($csv);
?>

 

I'm on an expert on CSV format, but I think all you need to do is quote your fields, and then the program that reads the data will ignore the newlines that are inbetween quotes. So I don't think that there is a bug in the code, you just need to quote your data.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.