-
- $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);
- }
Copy the code But there is no such built-in function in lower versions of PHP. You can implement a custom function yourself:
- 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;
- }
Copy the codeIn this way, the array read from the database can be converted into and written csv file
Code:
- $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));
- }
Copy code
|