Home > Backend Development > PHP Tutorial > Function example of php generating (exporting) csv file

Function example of php generating (exporting) csv file

WBOY
Release: 2016-07-25 08:55:07
Original
1072 people have browsed it
  1. $list = array (
  2. 'aaa,bbb,ccc,dddd',
  3. '123,456,789',
  4. '"aaa","bbb"'
  5. );
  6. $fp = fopen( 'file.csv', 'w');
  7. foreach ($list as $line) {
  8. fputcsv($fp, split(',', $line));
  9. fclose($fp);
  10. }
Copy the code

But there is no such built-in function in lower versions of PHP. You can implement a custom function yourself:

  1. function fputcsv4($fh, $arr){
  2. $csv = "";
  3. while (list($key, $val) = each($arr))
  4. {
  5. $ val = str_replace('"', '""', $val);
  6. $csv .= '"'.$val.'",';
  7. }
  8. $csv = substr($csv, 0, -1) ;
  9. $csv .= "n";
  10. if (!@fwrite($fh, $csv))
  11. return FALSE;
  12. }
Copy the code

In this way, the array read from the database can be converted into and written csv file

Code:

  1. $users = $this->mdMemUsers->findBysql($sql);
  2. $i = 0;
  3. foreach($users as $vo){
  4. $content[$ i] = implode(',',$vo);
  5. $i++;
  6. }
  7. $fp = fopen('users.csv', 'w');
  8. foreach ($content as $line) {
  9. fputcsv4($ fp, split(',', $line));
  10. }
Copy code


source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template