Jump to content

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.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.