- $list = array (
- 'aaa,bbb,ccc,dddd',
- '123,456,789',
- '"aaa","bbb"'
- );
- $fp = fopen('file.csv', 'w');
- foreach ($list as $line) {
- fputcsv($fp, split(',', $line));
- fclose($fp);
- }
不过低版本的php中没有这样的内置函数,可以自己实现一个自定义函数:
- function fputcsv4($fh, $arr){
- $csv = "";
- while (list($key, $val) = each($arr))
- {
- $val = str_replace('"', '""', $val);
- $csv .= '"'.$val.'",';
- }
- $csv = substr($csv, 0, -1);
- $csv .= "\n";
- if (!@fwrite($fh, $csv))
- return FALSE;
- }
如此就可以将数据库读出来的数组转化写入csv文件。
代码:
- $users = $this->mdMemUsers->findBysql($sql);
- $i = 0;
- foreach($users as $vo){
- $content[$i] = implode(',',$vo);
- $i++;
- }
- $fp = fopen('users.csv', 'w');
- foreach ($content as $line) {
- fputcsv4($fp, split(',', $line));
- }
|