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?
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";
}
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.
精彩评论