Home Backend Development PHP Tutorial PHP download generated csv file and problem summary_php skills

PHP download generated csv file and problem summary_php skills

May 16, 2016 pm 08:08 PM

最近做了一个项目需要把订单的信息显示出来,并且能够把相关信息放到一个.csv 文件中,下载到浏览器。虽然说csv是一种比较简单的excel表格形式,生成只要按指定格式然后生成.csv文件就可以,但是在使用中也会遇到很多问题,下面给大家分享下PHP下载csv文件及问题总结

首先大家先看个例子,生成csv文件并下载

//要生成csv文件的数组
$csvArr=array();
$csvArr[]=array('用户编号1','上班日期1','签到时间1','签退时间1');
$csvArr[]=array('用户编号2','上班日期2','签到时间2','签退时间2')
download_send_headers("data_export_" . date("Y-m-d") . ".csv");
$head=array('用户编号','上班日期','签到时间','签退时间');
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, 03 Jul 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");
}
Copy after login

php array生成csv文件

<&#63;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 => $val2) {
     $val[$key] = iconv('utf-8', 'gbk', $val2);
// CSV的Excel支持GBK编码,一定要转换,否则乱码
     }
      fputcsv($outputBuffer, $val);
    }
    fclose($outputBuffer);
  }
&#63;>
Copy after login

解决 fgetcsv函数在php5.2.8 中的bug

环境linux

问题解析出来的数据不完整,有为空的字段

网上查了下说是在php5.2.8 中存在bug

解决办法是使用自定义函数

function __fgetcsv(& $handle, $length = null, $d = ',', $e = '"') {
   $d = preg_quote($d);
   $e = preg_quote($e);
   $_line = "";
   $eof=false;
   while ($eof != true) {
     $_line .= (empty ($length) &#63; fgets($handle) : fgets($handle, $length));
     $itemcnt = preg_match_all('/' . $e . '/', $_line, $dummy);
     if ($itemcnt % 2 == 0)
       $eof = true;
   }
   $_csv_line = preg_replace('/(&#63;: |[ ])&#63;$/', $d, trim($_line));
   $_csv_pattern = '/(' . $e . '[^' . $e . ']*(&#63;:' . $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', '$1' , $_csv_data[$_csv_i]);
     $_csv_data[$_csv_i] = str_replace($e . $e, $e, $_csv_data[$_csv_i]);
   }
   return empty ($_line) &#63; false : $_csv_data;
}
Copy after login

excel无法正确读取长度超过32K的CSV域问题
php 导出csv文件用excel打开后,产品表述字段分两行显示。
查看了下这个字段发现这个字段超过32K的字符,excel会把字符串打断成两行,如果小于32K,显示正常。
这是EXCEL的限制,目前还没有找到解决办法。
excel一个单元格最多是32767个字符。
解决PHP生成UTF-8编码的CSV文件用Excel打开乱码的问题
PHP生成UTF-8编码的CSV文件用Excel打开中文显示乱码,是由于输出的CSV文件中没有BOM。

<&#63;php
$now = gmdate("D, d M Y H:i:s");
header("Expires: Tue, 03 Jul 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));
//设置utf-8 + bom ,处理汉字显示的乱码
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();
}
&#63;>
Copy after login

导出csv文件数字会自动变科学计数法的解决方法
用程序导出的csv文件,当字段中有比较长的数字字段存在时,在用excel软甲查看csv文件时就会变成科学技术法的表现形式。
其实这个问题跟用什么语言导出csv文件没有关系。Excel显示数字时,如果数字大于12位,它会自动转化为科学计数法;如果数字大于15位,它不仅用于科学技术费表示,还会只保留高15位,其他位都变0。
解决这个问题
只要把数字字段后面加上显示上看不见的字符即可,字符串结尾加上制表符"\t".
php 程序可以这样判断,注意一定是"\t",不是'\t'.

复制代码 代码如下:

is_numeric($val)?$val."\t":$val;

以上代码内容就是本文实现PHP下载生成的csv文件及问题总结,希望大家喜欢。

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

See all articles