export to csv (SOLVED in a way!)

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
sirTemplar
Forum Commoner
Posts: 65
Joined: Wed Dec 18, 2002 1:57 am

export to csv (SOLVED in a way!)

Post by sirTemplar »

i have a script that queries my MySql database, after the search and output i would like to be able to export the result into a csv format. is this possible and how? thank you
Last edited by sirTemplar on Mon Sep 15, 2008 8:54 am, edited 1 time in total.
User avatar
dude81
Forum Regular
Posts: 509
Joined: Mon Aug 29, 2005 6:26 am
Location: Pearls City

Re: export to csv

Post by dude81 »

Yes, it is possible, for "export to csv" search this forum that could through you huge results.
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Re: export to csv

Post by pickle »

fputcsv() is a nice function if your system is up to date.
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
sirTemplar
Forum Commoner
Posts: 65
Joined: Wed Dec 18, 2002 1:57 am

Re: export to csv

Post by sirTemplar »

thank you. searching the net, i found the following code. it does what i want just that it's exporting ALL FIELDS, and is TAB separated. i want to separate it with a comma (,) and export only some fields.

Code: Select all

 
$export = mysql_query ( $select ) or die ( "Sql error : " . mysql_error( ) );
 
$fields = mysql_num_fields ( $export );
 
for ( $i = 0; $i < $fields; $i++ )
{
$header .= mysql_field_name( $export , $i ) . "\t";
}
 
while( $row = mysql_fetch_row( $export ) )
{
$line = '';
foreach( $row as $value )
{
if ( ( !isset( $value ) ) || ( $value == "" ) )
{
$value = "\t";
}
else
{
$value = str_replace( '"' , '""' , $value );
$value = '"' . $value . '"' . "\t";
}
$line .= $value;
}
$data .= trim( $line ) . "\n";
}
$data = str_replace( "\r" , "" , $data );
 
if ( $data == "" )
{
$data = "\n(0) Records Found!\n";
}
 
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=database.xls");
header("Pragma: no-cache");
header("Expires: 0");
print "$header\n$data";
 
Post Reply