doushenyu2537 2019-02-14 08:25
浏览 24

在php中将数组字符串转换为csv

I have an array with string array("firstname" => "Mary", "lastname" => "Johnson", "age" => '0025') i want to export to csv file but i got no 0 like this 25 when i export to csv file.

i try these code and i got result without 0

$data = array(
    array("firstname" => "Mary", "lastname" => "Johnson", "age" => '0025')
  );

  $colnames = array(
    'firstname' => "Fname",
    'lastname' => "Last name",
    'age' => "Age",
  );

  function map_colnames($input)
  {
    global $colnames;
    return isset($colnames[$input]) ? $colnames[$input] : $input;
  }

  function cleanData(&$str)
  {
    if($str == 't') $str = 'TRUE';
    if($str == 'f') $str = 'FALSE';
    if(preg_match("/^0/", $str) || preg_match("/^\+?\d{8,}$/", $str) || preg_match("/^\d{4}.\d{1,2}.\d{1,2}/", $str)) {
      $str = "$str";
    }
    if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';
  }

  // filename for download
  $filename = "website_data_" . date('Ymd') . ".csv";

  header("Content-Disposition: attachment; filename=\"$filename\"");
  header("Content-Type: text/csv");

  $out = fopen("php://output", 'rw');

  $flag = false;
  foreach($data as $row) {
    if(!$flag) {
      // display field/column names as first row
      $firstline = array_map(__NAMESPACE__ . '\map_colnames', array_keys($row));
      fputcsv($out, $firstline, ',', '"');
      $flag = true;
    }
    array_walk($row, __NAMESPACE__ . '\cleanData');
    fputcsv($out, array_values($row), ',', '"');
  }

  fclose($out);
  exit;

i got these result

Fname   Lastname   Age
MAry    Johnson    25

Any solution for this?

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥100 连续两帧图像高速减法
    • ¥15 组策略中的计算机配置策略无法下发
    • ¥15 如何绘制动力学系统的相图
    • ¥15 对接wps接口实现获取元数据
    • ¥20 给自己本科IT专业毕业的妹m找个实习工作
    • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
    • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
    • ¥50 mac mini外接显示器 画质字体模糊
    • ¥15 TLS1.2协议通信解密
    • ¥40 图书信息管理系统程序编写