tags:

views:

39

answers:

2

i have a database table where i have store different information and i want to make a csv file from it how can i do this?

+1  A: 

If the database is MySQL, try this:

SELECT a,b,a+b INTO OUTFILE '/tmp/result.txt'
  FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
  LINES TERMINATED BY '\n'
  FROM test_table;

(code snippet from http://dev.mysql.com/doc/refman/5.0/en/select.html )

Or you can do it in application code like this:

$fh = fopen('file.csv', 'w');
$rows = $db->query('select first_name, last_name, email, telephone, company_name, customer_id, city from customer_tab;');

while($r = $rows->fetch_assoc()) {
        fputcsv($fh, $r);
}
fclose($fh);

or in PHP < 5.1:

$rows = $db->query('select first_name, last_name, email, telephone, company_name, customer_id, city from customer_tab;');

while($r = $rows->fetch_assoc()) {
        $i = 0;
        foreach($r as $k => $v) {
                $v = trim($v);
                echo "\"$v\"";
                if($i++ < 6) {
                        echo ",";
                }
        }
        echo "\n";
}
Emil Vikström
Good answer - but be aware that CSV is NOT a file format - its LOTS of similar file formats. There is a text/csv mime-type - which does not deal with escaping meta-data and even then only addresses a tiny subset of the actuakl formats described as CSV. And of course Microsoft's CSV is different from everyone elses too!
symcbean
A: 

There are several ways to accomplish this. You can do it "manually", with which I mean you format the output and write it to disk. You can use fputcsv to write an array as a csv-formatted line. You can use PEAR's File_CSV. Or you can use whatever Google will find for you.

nikc