fputcsv() 函数将行格式化为 CSV 并写入一个打开的文件,该函数返回写入字符串的长度,若出错,则返回 false.
说明:fputcsv() 将一行(用 fields 数组传递)格式化为 CSV 格式并写入由 file 指定的文件.
PHP实例代码如下:
-
- header('Content-Type: application/vnd.ms-excel');
- header('Content-Disposition: attachment;filename="user.csv"');
- header('Cache-Control: max-age=0');
-
-
- $sql = 'select * from tbl where ……';
- $stmt = $db->query($sql);
-
-
- $fp = fopen('php://output', 'a');
-
-
- $head = array('姓名', '性别', '年龄', 'Email', '电话', '……');
- foreach ($head as $i => $v) {
-
- $head[$i] = iconv('utf-8', 'gbk', $v);
- }
-
-
- fputcsv($fp, $head);
-
-
- $cnt = 0;
-
- $limit = 100000;
-
-
- while ($row = $stmt->fetch(Zend_Db::FETCH_NUM)) {
-
- $cnt ++;
- if ($limit == $cnt) {
- ob_flush();
- flush();
- $cnt = 0;
- }
-
- foreach ($row as $i => $v) {
- $row[$i] = iconv('utf-8', 'gbk', $v);
- }
- fputcsv($fp, $row);
- }
|