- $ List = array (
- 'AAA, bbb, ccc, dddd ',
- '123 ',
- '"Aaa", "bbb "'
- );
- $ Fp = fopen('file.csv ', 'w ');
- Foreach ($ list as $ line ){
- Fputcsv ($ fp, split (',', $ line ));
- Fclose ($ fp );
- }
However, this built-in function is not available in earlier versions of php. you can implement a custom function by 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;
- }
In this way, the array read from the database can be converted into a 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 ));
- }
|