Home > Backend Development > PHP Tutorial > PHP exports csv with leading 0 examples to share

PHP exports csv with leading 0 examples to share

*文
Release: 2023-03-18 22:42:01
Original
1606 people have browsed it

How does php export a csv file with leading 0s? The editor below will bring you an article about exporting csv files from php, which can export leading 0 example code. The editor thinks it’s pretty good, so I’ll share it with you now and give it as a reference. I hope to be helpful.

Example 1: Leading 0 can be exported

//导出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 .= &#39;"&#39; . $title_arr[$i] . &#39;",&#39;;
  }
  if ($nums > 0) {
    $csv_data .= &#39;"&#39; . $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] . &#39;",&#39;;
    }

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

Note: Hyperlinks cannot be output directly!

Related recommendations:

php csv operation class code

php csv to array(csv to array) method and code

PHP CSV import database

The above is the detailed content of PHP exports csv with leading 0 examples to share. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template