PHP Download generated CSV file and problem summary _php tips

Source: Internet
Author: User
Tags chr php download

Recently, a project has been done to show the order information and to put the relevant information in a. csv file and download it to the browser. Although the CSV is a relatively simple form of Excel tables, generate only in the specified format and then generate a. csv file, but in use will also encounter a lot of problems, the following to share PHP download CSV file and the summary of the problem

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

The array to generate the CSV file $csvArr =array ();
$CSVARR []=array (' User number 1 ', ' Work date 1 ', ' check-in time 1 ', ' check-in time 1 '); $CSVARR []=array (' User ID 2 ', ' Work date 2 ', ' check-in time 2 ', ' check-in time 2 ') download_send_headers ("Data_export_". Date ("y-m-d").
". csv");
$head =array (' User number ', ' date of work ', ' check-in time ', ' check-out time ');
Echo array2csv ($CSVARR, $head);
Unset ($CSVARR);
Die ();
  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 ();
  The function download_send_headers ($filename) {//disable caching $now = Gmdate ("D, D M Y h:i:s");
  Header ("Expires:tue, June 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 generates 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 Excel supports GBK encoding, be sure to convert, otherwise garbled
     }
      fputcsv ($outputBuffer, $val);
    }
    Fclose ($outputBuffer);
>

Resolving bugs in php5.2.8 fgetcsv functions

Environment Linux

The problem parsed out of the data is incomplete and has an empty field

I checked it on the Internet, and there was a bug in php5.2.8.

The

Workaround is to use custom functions

 function __fgetcsv (& $handle, $length = null, $d = ', ', $e = ' "') {$d = Preg_quot
   E ($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 with a length of more than 32K
PHP export CSV file when opened with Excel, the Product presentation field is displayed in two lines.
Look at this field found this field more than 32K characters, Excel will break the string into two lines, if less than 32K, display 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.
to troubleshoot PHP generated UTF-8 encoded CSV file with Excel to open garbled questions
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, June 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"); $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, processing Chinese character display garbled echo array2csv ($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 a CSV file number will automatically change the method of scientific counting method
The CSV file exported by the program, when the field has a relatively long number of fields exist, in 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 what language to export CSV files. When Excel displays a number, if the number is greater than 12 digits, it is automatically converted to scientific notation; If the number is greater than 15 digits, it is not only used for science and technology fees, but also for the high 15 digits, and the other bits are 0.
Solve this problem
As long as the number field followed by the display of invisible characters, the end of the string plus the tab "\ T".
The PHP program can be so judged, note must be "\ T", not ' t '.

Copy Code code as follows:

Is_numeric ($val) $val. " \ t ": $val;

The above code content is this article realizes the PHP download produces the CSV file and the question summary, hoped everybody likes.

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.