开发者

how to make a csv file from database in php? [closed]

开发者 https://www.devze.com 2023-01-02 00:55 出处:网络
开发者_StackOverflow中文版It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical andcannot be reasonably answered in its cu
开发者_StackOverflow中文版 It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 10 years ago.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消