Export Query results to CSV

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
new2phpcode
Forum Newbie
Posts: 21
Joined: Tue Oct 09, 2007 10:40 pm

Export Query results to CSV

Post by new2phpcode »

Hi is there anyone who has made a script to export query results from postgres sql to CSV , with a button that says download then a save as window box will appear so they can choose where the file would be save locally? im not pretty sure how this is called.... :?: Thanks!
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: Export Query results to CSV

Post by Christopher »

Usually something like this will work:

Code: Select all

echo implode("\t", $row) . "\n";
//or 
echo '"' . implode('","', $row) . "\"\n";
Set the right header() and then loop though the results and echo the rows.
(#10850)
new2phpcode
Forum Newbie
Posts: 21
Joined: Tue Oct 09, 2007 10:40 pm

Re: Export Query results to CSV

Post by new2phpcode »

im not pretty sure how to do this, but its worth to try.. is there a working sample? :D thanks!
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: Export Query results to CSV

Post by Christopher »

The PHP manual is usually a good place to start. Check the pages for header() and implode() for examples.
(#10850)
new2phpcode
Forum Newbie
Posts: 21
Joined: Tue Oct 09, 2007 10:40 pm

Re: Export Query results to CSV

Post by new2phpcode »

thanks aborint for the help! i got the code!

Code: Select all

 
$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;
 
Post Reply