Web Hosting Talk







View Full Version : Generating CSV Files


AdWatcher-Boris
02-20-2005, 02:49 AM
Greetings,

I was curious - we have a database with various information that we would like to allow users to export as a CSV file.

However, I'm having difficulties finding information on the specifics and techniques of doing so. Anybody has any advice oe tips on how to generate CSV files with information from the DB?

Boris

error404
02-20-2005, 05:50 PM
It should be pretty trivial. Select the data into an array, and for each row in the array, join the columns with ',' and then print a newline.

In PHP, for example:

$file = fopen('foo.csv', 'w') or die('Unable to open file');
$rows = mysql_query('SELECT * FROM foo');
while ($r = mysql_fetch_array($rows))
{
fwrite($file, implode(',', $r) . "\n");
}
mysql_free_result($rows);
fclose($file);

toweter
02-20-2005, 06:00 PM
but this is not working if there are commas in the database, is it?

i'm not further experienced in working with *.csv files, but if the syntax used by microsoft excel isn't wrong this should work:
$file = fopen('foo.csv', 'w') or die('Unable to open file');
$rows = mysql_query('SELECT * FROM foo');
while ($r = mysql_fetch_array($rows))
{
for($x = 0; $x < count($r); $x++)
{
if (eregi(",", $r[$x]))
{
$r[$x] = '"'.$r[$x].'"';
}
}
fwrite($file, implode(',', $r) . "\n");
}
mysql_free_result($rows);
fclose($file);