PHP generate CSV file and download and problem summary

Source: Internet
Author: User
Tags foreach chr reset

example, generate a CSV file and download

To generate an array of CSV files
$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-out 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 ();
}

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 (
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 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 read the CSV domain problem with a length exceeding 32K correctly

After the PHP export CSV file is opened in Excel, the Product presentation field is displayed in two lines.
See the next field found this field more than 32K characters, Excel will break the string into two lines, if less than 32K, display normal.
This is the limit of Excel and no solution has been found yet.
Excel is a cell with a maximum of 32,767 characters.


solve 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 due to 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 to handle the garbled characters displayed
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 '.
Is_numeric ($val) $val. " \ t ": $val;

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.