Home  >  Article  >  Backend Development  >  PHP exports csv files, leading 0 instances can be exported

PHP exports csv files, leading 0 instances can be exported

墨辰丷
墨辰丷Original
2018-05-30 17:44:071461browse

This article mainly introduces php to export csv files, which can export leading 0 examples. Interested friends can refer to it. I hope it will be helpful to everyone.

Example 1: Exportable leading 0

//导出csv格式文件 $data数据 $title_arr标题 $file_name文件名
function exportCsv($data,$title_arr,$file_name=''){
  ini_set("max_execution_time", "3600");

  $csv_data = '';
  /** 标题 */
  $nums = count($title_arr);

  for ($i = 0; $i < $nums - 1; ++$i) {
    $csv_data .= '"' . $title_arr[$i] . '",';
  }
  if ($nums > 0) {
    $csv_data .= '"' . $title_arr[$nums - 1] . "\"\r\n";
  }

  foreach ($data as $k => $row) {
    foreach ($row as $key => $r){

      $row[$key] = str_replace("\"", "\"\"", $r);

      $csv_data .= "\"\t" . $row[$key] . '",';
    }

    $csv_data .= '"' . $row[$nums - 1] . "\"\r\n";
    unset($data[$k]);
  }
  $csv_data = mb_convert_encoding($csv_data, "cp936", "UTF-8");
  $file_name = empty($file_name) ? date('Y-m-d-H-i-s', time()) : $file_name;
  if (strpos($_SERVER['HTTP_USER_AGENT'], "MSIE")) { // 解决IE浏览器输出中文名乱码的bug
    $file_name = urlencode($file_name);
    $file_name = str_replace('+', '%20', $file_name);
  }
  $file_name = $file_name . '.csv';
  header('Content-Type: application/download');
  header("Content-type:text/csv;");
  header("Content-Disposition:attachment;filename=" . $file_name);
  header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
  header('Expires:0');
  header('Pragma:public');
  echo $csv_data;
  exit();
}

Comment: No Hyperlinks can be output directly!

The above is the entire content of this article, I hope it will be helpful to everyone's study.


Related recommendations:

PHP method to implement clockwise printing of matrices and spiral matrices

PHP learning: details of predefined variables

php How to quickly remove duplicates from array elements

The above is the detailed content of PHP exports csv files, leading 0 instances can be exported. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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