PHP Download generated CSV file and problem summary, _php tutorial

Source: Internet
Author: User
Tags php download

PHP Download generated CSV file and summary of the problem,


Recently, a project has been made to display the information of the order and to be able to put the relevant information into a. csv file and download it to the browser. Although CSV is a relatively simple form of Excel form, generated as long as the specified format and then generate a. csv file can be, but in use also encounter a lot of problems, below for everyone to share the next PHP download csv file and problem summary

First, let's look at an example, generate a CSV file and download

To generate an array of CSV files $csvarr=array (); $csvArr []=array (' User number 1 ', ' 1 ', ' check-in time 1 ', ' Checkout time 1 '), $CSVARR []=array (' User number 2 ', ' Work date 2 ', ' Sign-in time 2 ', ' Checkout Time 2 ') download_send_headers ("Data_export_". Date ("y-m-d"). ". csv"), $head =array (' User number ', ' Work Date ', ' sign-in time ', ' check-out time '); Echo array2csv ($CSVARR, $head); unset ($CSVARR);d ie (); function  Array2csv (Array & $array, $head) {if (count ($array) = = 0) {return null;  } ob_start ();  $DF = fopen ("Php://output", ' W ');  if (! $head) {$head =array_keys (reset ($array));  } fputcsv ($DF, $head);  foreach ($array as $row) {fputcsv ($DF, $row);  } fclose ($DF); return Ob_get_clean ();}  function Download_send_headers ($filename) {//disable caching $now = Gmdate ("D, D M Y h:i:s");  Header ("Expires:tue, 2001 06:00:00 GMT");  Header ("Cache-control:max-age=0, No-cache, Must-revalidate, proxy-revalidate");  Header ("last-modified: {$now} GMT");  Force Download header ("Content-type:application/force-download");  Header ("Content-type:application/octet-stream"); Header ("Content-type:aPplication/download ");  Disposition/encoding on response body header ("content-disposition:attachment;filename={$filename}"); Header ("Content-transfer-encoding:binary");}

PHP array to generate CSV file

<?php$data = Array (    ' row_1_col_1 ', ' row_1_col_2 ', ' row_1_col_3 '),    array (' Row_2_col_1 ', ' Row_2_col_ 2 ', ' Row_2_col_3 '),    array (' Row_3_col_1 ', ' row_3_col_2 ', ' row_3_col_3 '),  $filename = "Example";  Header ("Content-type:text/csv");  Header ("content-disposition:attachment; filename={$filename}.csv ");  Header ("Pragma:no-cache");  Header ("expires:0"), Outputcsv ($data), function outputcsv ($data) {    $outputBuffer = fopen ("Php://output", ' W ');    foreach ($data as $val) {    foreach ($val as $key = $val 2) {     $val [$key] = iconv (' utf-8 ', ' GBK ', $val 2);//CSV E Xcel Support GBK encoding, be sure to convert, otherwise garbled     }      fputcsv ($outputBuffer, $val);    }    Fclose ($outputBuffer);  }? >

Fix the bug in php5.2.8 of Fgetcsv function

Environment Linux

The problem resolves the data is incomplete, there is an empty field

I checked it online and there was a bug in the php5.2.8.

The workaround is to use a custom function

function __fgetcsv (& $handle, $length = null, $d = ', ', $e = ' "') {$d = Preg_quote ($d);   $e = Preg_quote ($e);   $_line = "";   $eof =false;     while ($eof! = True) {$_line. = (Empty ($length)? Fgets ($handle): Fgets ($handle, $length)); $itemcnt = Preg_match_all ('/'. $e.     '/', $_line, $dummy);   if ($itemcnt% 2 = = 0) $eof = true; } $_csv_line = Preg_replace ('/(?: |[])?   $/', $d, Trim ($_line)); $_csv_pattern = '/('. $e. ' [^ '. $e. ']* (?: '. $e. $e. ' [^ '. $e. ']*)*' . $e. '| [^ '. $d. ']*)' . $d.   '/';   Preg_match_all ($_csv_pattern, $_csv_line, $_csv_matches);   $_csv_data = $_csv_matches[1]; for ($_csv_i = 0; $_csv_i < count ($_csv_data); $_csv_i++) {$_csv_data[$_csv_i] = preg_replace ('/^ '. $e. '(.*)' . $e.     ' $/s ', ' $ ', $_csv_data[$_csv_i]);   $_csv_data[$_csv_i] = Str_replace ($e. $e, $e, $_csv_data[$_csv_i]); } return empty ($_line)? False: $_csv_data;} 

Excel cannot correctly read a CSV domain problem that is longer than 32K
when you open the PHP export CSV file in Excel, the Product Description field appears in two lines.
View the next field to find this field more than 32K characters, Excel will break the string into two lines, if less than 32K, the display is normal.
This is a limitation of Excel and no workaround has been found yet.
Excel is a cell with a maximum of 32,767 characters.
fix PHP generated UTF-8 encoded CSV file with Excel open garbled problem
PHP generated UTF-8 encoded CSV file with Excel Open Chinese display garbled, is because the output of the CSV file does not have a BOM.

<?php$now = Gmdate ("D, D M Y h:i:s"), Header ("Expires:tue, Jul 2001 06:00:00 GMT"), Header ("Cache-control:max-age=0, No-cache, Must-revalidate, proxy-revalidate "), Header (" Last-modified: {$now} GMT ");//Force Downloadheader (" Content-type:application/force-download "); Header (" Content-type:application/octet-stream "); Header (" Content-Type : Application/download ");//disposition/encoding on response Bodyheader (" content-disposition:attachment;filename={$ filename} "), Header (" Content-transfer-encoding:binary "), $items _data=array (' 0 ' =>array (' title ' = ' = ' test test Test1 '), ' 1 ' =>array (' title ' = ' = ' test test test2 '), ' 2 ' =>array (' title ' = ' test test test3 ') ' Print (Chr (0xEF). Chr (0xBB). Chr (0xBF)),//set Utf-8 + BOM, handle the garbled character display of array2csv Echo ($items _data); function array2csv (array & $array) {if (  Count ($array) = = 0) {return null;  } ob_start ();  $DF = fopen ("Php://output", ' W ');  Fputcsv ($DF, Array_keys (Reset ($array)));  foreach ($array as $row) {fputcsv ($DF, $row); } fclose ($DF);  return Ob_get_clean ();}? >

Export CSV file numbers will automatically change the method of scientific counting method
CSV file exported by the program, when the field has a longer number field exists, when using the Excel soft armor to view the CSV file will become a form of scientific and technical law.
In fact, this question is not related to the export of CSV files in any language. When Excel displays a number, if the number is greater than 12 bits, it is automatically converted to scientific notation, and if the number is greater than 15, it is used not only for science and technology fee representations, but also for the high 15 bits, and the other bits to 0.
Solve this problem
As long as the number field is followed by an invisible character, the end of the string is preceded by a tab "\ T".
PHP program can be judged this way, note must be "\ T", not ' \ t '.

Copy the Code code as follows:
Is_numeric ($val)? $val. " \ t ": $val;

The above code content is to implement PHP download generated CSV file and the problem summary, I hope you like.

http://www.bkjia.com/PHPjc/1044255.html www.bkjia.com true http://www.bkjia.com/PHPjc/1044255.html techarticle PHP Download generated CSV file and problem summary, recently done a project need to show the order information, and can put the relevant information in a. csv file, download to the browser ...

  • 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.