PHP generates a CSV file

Source: Internet
Author: User
This article introduces the content is about PHP generated CSV file, has a certain reference value, now share to everyone, the need for friends can refer to

Needless to say, the dry stuff.

Method One:

/** * Export Excel (CSV) * @data Export Data * @headlist first row, column name * @fileName output Excel file name */function csv_export ($data = Array (), $headlist     = Array (), $fileName) {header (' content-type:application/vnd.ms-excel '); Header (' Content-disposition:attachment;filename= '. $fileName. '.     CSV "');     Header (' cache-control:max-age=0 '); Open PHP file Handle, php://output indicates direct output to browser $fp = fopen (' php://output ', ' a ');//Open file resource, do not exist then create//Output Excel column name information foreach ($ Headlist as $key + $value) {//csv Excel supports GBK encoding, be sure to convert otherwise garbled $headlist [$key] = iconv (' utf-8 ', ' GBK ', $va     Lue);     }//Writes data through Fputcsv to the file handle Fputcsv ($FP, $headlist);     Counter $num = 0;     Every $limit line, refresh the output buffer, not too big, not too small $limit = 100000;     Data is fetched row by line without wasting memory $count = count ($data);         for ($i = 0; $i < $count; $i + +) {$num + +;              Refresh the output buffer to prevent problems caused by excessive data if ($limit = = $num) {Ob_flush ();               Flush ();            $num = 0;   } $row = $data [$i];         foreach ($row as $key = + $value) {$row [$key] = iconv (' utf-8 ', ' GBK ', $value);        } fputcsv ($fp, $row); }    }

Method Two:

Public Function Getexportlog () {if (! $this->valid_admin (@$_server [' Php_auth_user '], @$_server [' PHP_AUTH_PW '])) {//$_server [' php_auth_user '] browser accepts username input header (' Www-authenticate:basic realm= "");//Browser popup Enter user name password prompt box header      (' http/1.0 401 Unauthorized ');      echo "You need to enter a valid username and password.";   Exit ();       } $oViewLog = new Dbspatientviewlog ();      $result = $oViewLog->getallinfo ();   $sname = time ();   $dataname =date (' Ymd '); $exportdir = Public_path (). " /exportfile/". $dataname."   /";      if (!is_dir ($exportdir)) {mkdir ($exportdir, 0777,true); }//Generate CSV file $elsfile = $exportdir. $sname.          CSV ';          $fp = fopen ($elsfile, ' w ');          $data = "";          $title =implode (', ', ' Array (' Medical pulse ID ', ' Medical pulse id ', ' article ID ', ' participating activities ', ' time to visit the Activity homepage ', ' time to access the Record Information page ', ' participating in the activity ');          $data = $title;                               foreach ($result as $value) {$line =implode (', ', Array ($value [' Meduid_old '],    $value [' Meduid '], $value [' MsgId '], $value [' Hd_wa Y ']==1? ' Suspected patient referral ': ' des strips ', $value [' View_at '], $value [' View_at_ Show '], $value [' View_way ']==1? ' Mobile ': $value [' View_way ']==2? '                     Browser ': ' PC ',)); $data = $data. "              \ r \ n ". $line;      } $data =iconv ("UTF-8", "Gbk//ignore", $data); Fwrite ($fp, $data); Write Data fclose ($FP); Close the file handle $download _dir= "/exportfile/". $dataname. ' /'. $sname. '.          CSV ';       Header ("Content-type:text/csv"); Header ("Content-disposition:attachment;filename=". $sname.       CSV ');       Header (' cache-control:must-revalidate,post-check=0,pre-check=0 ');       Header (' expires:0 ');       Header (' Pragma:public '); echo $data;}

Although the above two methods, can actually be regarded as a kind of

Process:

1. Use the fopen () function to open the specified file, no creation file exists

2, the title processing, is an array of words, you can directly use Fputcsv () as the first code to write the data directly to the file handle, or use the second paragraph of code using the implode () function to split

3, the data processing, the first paragraph is the data one row of data format converted to write to the file, the second paragraph is implode () split data, the whole data is finally stitched together, the conversion format to write data; Note: fwrite () writes data

4. Close file handle

Summary: The process of generating a CSV file is so, I recommend the first, save memory, and periodically refresh the output buffer, to prevent the problem caused by too much data

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.