PHP 导出cvs文件

iconv用法:https://www.php.net/manual/zh/function.iconv.php

iconv

(PHP 4 >= 4.0.5, PHP 5, PHP 7)

iconv — 字符串按要求的字符编码来转换

说明

iconv ( string $in_charset , string $out_charset , string $str ) : string

将字符串 strin_charset 转换编码到 out_charset

参数

in_charset

输入的字符集。

out_charset

输出的字符集。

如果你在 out_charset 后添加了字符串 //TRANSLIT,将启用转写(transliteration)功能。这个意思是,当一个字符不能被目标字符集所表示时,它可以通过一个或多个形似的字符来近似表达。 如果你添加了字符串 //IGNORE,不能以目标字符集表达的字符将被默默丢弃。 否则,会导致一个 E_NOTICE并返回 FALSE

Caution

//TRANSLIT 运行细节高度依赖于系统的 iconv() 实现(参见 ICONV_IMPL)。 据悉,某些系统上的实现会直接忽略 //TRANSLIT,所以转换也有可能失败,out_charset 会是不合格的。

str

要转换的字符串。

注:运用//TRANSLIT 的话,空格是不能识别的,转换会报错。

-----------------------------------------------------------------------------------------------------------------------------------------------

方法一:

/**
 * 导出excel(csv)
 * @data 导出数据
 * @headlist 第一行列名(注意前两个列名不能是大写!否则输出的扩展名不是cvs)
 * @fileName 输出Excel文件名
 */

function csv_export($data = array(), $headlist = array(), $fileName) {

    header('Content-Type: application/vnd.ms-excel');
    header('Content-Disposition: attachment;filename="'.$fileName.'.csv"');
    header('Cache-Control: max-age=0');

    //打开PHP文件句柄,php://output 表示直接输出到浏览器
    $fp = fopen('php://output', 'a');// 打开文件资源,不存在则创建

    //输出Excel列名信息
    foreach ($headlist as $key => $value) {
        //CSV的Excel支持GBK编码,一定要转换,否则乱码
        $headlist[$key] = iconv('utf-8', 'gbk', $value);
    }

    //将数据通过fputcsv写到文件句柄
    fputcsv($fp, $headlist);

    //计数器
    $num = 0;

    //每隔$limit行,刷新一下输出buffer,不要太大,也不要太小
    $limit = 100000;

    //逐行取出数据,不浪费内存
    $count = count($data);
    for ($i = 0; $i < $count; $i++) {

        $num++;

        //刷新一下输出buffer,防止由于数据过多造成问题
        if ($limit == $num) {
            ob_flush();
            flush();
            $num = 0;
        }

        $row = $data[$i];
        foreach ($row as $key => $value) {
            $row[$key] = iconv('utf-8', 'gbk', trim($value)); 
        }

        fputcsv($fp, $row);
    }
}


方法二:

public function getExportLog(){
   if (! $this->valid_admin ( @$_SERVER ['PHP_AUTH_USER'], @$_SERVER ['PHP_AUTH_PW'] )) {//$_SERVER ['PHP_AUTH_USER']浏览器接受的用户名输入
      header ( 'WWW-Authenticate: Basic realm=""' );//浏览器弹出输入用户名密码提示框
      header ( 'HTTP/1.0 401 Unauthorized' );
      echo "You need to enter a valid username and  password.";
      exit ();
   }

       $oViewLog = new DbsPatientViewLog();
       $result = $oViewLog->getAllInfo();
   
   $sname =  time();
   $dataname=date('Ymd');
   $exportdir = public_path()."/exportfile/".$dataname."/";
   if(!is_dir($exportdir))
   {
      mkdir($exportdir,0777,true);   
   }
   //生成csv文件
   $elsfile=$exportdir.$sname.'.csv';
       $fp = fopen($elsfile, 'w');
       $data="";
       $title=implode(',', array('医脉通加密ID','医脉通ID','文章ID','参与的活动','访问活动首页的时间','访问记录信息页面的时间','参与活动的方式'));
       $data=$title;
       foreach($result as $value)
       {
           $line=implode(',', array($value['meduid_old'],
                             $value['meduid'],
                             $value['msgid'],
                             $value['hd_way']==1?'疑似患者转诊':'DES试纸',
                             $value['view_at'],
                             $value['view_at_show'],
                             $value['view_way']==1?'mobile':$value['view_way']==2?'微信浏览器': 'PC',
                                  )
           );
              $data=$data."\r\n".$line;
       }
       $data=iconv("UTF-8", "GBK//IGNORE", $data);
      fwrite($fp,$data); // 写入数据
      fclose($fp); //关闭文件句柄
   $download_dir= "/exportfile/".$dataname.'/'.$sname.'.csv';
   header("Content-type:text/csv");   
    header("Content-Disposition:attachment;filename=".$sname.'.csv');   
    header('Cache-Control:must-revalidate,post-check=0,pre-check=0');   
    header('Expires:0');   
    header('Pragma:public');   
    echo $data;
}
-------------------------------------------------------------------------------------------------------------------------------------------------

流程:

1、使用fopen()函数,打开指定文件,不存在创建文件

2、对标题进行处理,是数组的话,可以像第一段代码一样直接使用fputcsv()直接将数据写到文件句柄中去;或者使用第二段代码使用implode()函数分割

3、对数据的处理,第一段是将数据一行一行数据格式转换后写入文件;第二段是implode()分割数据,数据整体最终拼接在一起,转换格式写入数据;         注:fwrite()写入数据

4、关闭文件句柄

总结:生成csv文件流程就是如此,本人推荐第一种,省内存,且定期刷新输出buffer,防止数据过多造成的问题
---------------------------------------------------------------------------------------------------------------------------------------------------
还有别的导出功能方式:
第一种写法:
视图:
οnclick="window.location.href='/admin/video/export'"
控制器:
set_time_limit(0);
header('Cache-control:public');
header('Pragma:public');
header('Content-type:application/vnd.ms-excel');
header('Content-Disposition:attachment;filename=works_info_'.date('Ymdhis').'.csv');
header('Content-Type:APPLICATION/OCTET-STREAM');
ob_start();
$header_str=iconv('utf-8','gbk',"视频id,视频标题,视频分类,专家姓名,专家专业,专家医院,本期视频观看的总次数,本期视频观看的总时长\n");
$file_str='';
$oViodes=Video::All();
if ($oViodes){
    foreach ($oViodes as $k=>$v){
        $view_length=Viewlog::where('video_id',$v->id)->sum('video_length');
        $file_str.=$v->id.',';
        $file_str.=$v->caption.',';
        $file_str.=$v->class.',';
        $file_str.=$v->expert_name.',';
        $file_str.=$v->profession.',';
        $file_str.=$v->hospital.',';
        $file_str.=isset($v->browse_count) ? $v->browse_count.',' : ''.',';
        $file_str.=isset($view_length) ? $view_length."\n" : ''."\n" ;
    }
    $file_str=iconv('utf-8','GBK//TRANSLIT',$file_str);
    ob_end_clean();
    echo $header_str;
    echo $file_str;
}
第二种写法:
视图:
οnclick="exportcsv()"

function exportcsv()
{
   $.get("/admin/video/export",function(data)
      {
      window.location.href=data;
      window.event.returnValue = false;

      });
}

控制器:
$oVideos=Video::All();
$sname =  time();
$dataname=date('Ymd');
$exportdir = public_path()."/exportfile/".$dataname."/";
if(!is_dir($exportdir))
{
   mkdir($exportdir,0777,true);   
}
//生成csv文件
$elsfile=$exportdir.$sname.'.csv';
      $fp = fopen($elsfile, 'w');
      $data="";
      $title=implode(',', array('视频id','视频标题','视频分类','专家姓名','专家专业','专家医院','本期视频观看的总次数','本期视频观看的总时长'));
      $data=$title;
      foreach($oVideos as $cf)
      {
       $view_length=Viewlog::where('video_id','=',$cf->id)->sum('video_length');
       $line=implode(',', array(isset($cf->id) ? $cf->id :'',
                         isset($cf->caption) ? $cf->caption : '',
                         isset($cf->class) ? $cf->class : '',
                         isset($cf->expert_name) ? $cf->expert_name : '',
                         isset($cf->profession) ? $cf->profession : '',
                         isset($cf->hospital) ? $cf->hospital : '',
                         isset($cf->browse_count) ? $cf->browse_count : '',
                         isset($view_length) ? $view_length : '',
                         ));
          $data=$data."\r\n".$line;
      }
      $data=mb_convert_encoding($data, "GBK", "UTF-8");//iconv("UTF-8", "GBK//IGNORE", $data);   
   fwrite($fp,$data); // 写入数据
   fclose($fp); //关闭文件句柄
$download_dir= "/exportfile/".$dataname.'/'.$sname.'.csv';
return $download_dir;
---------------------
作者:不二周助Rex
来源:CSDN
原文:https://blog.csdn.net/weixin_42188216/article/details/83899445
版权声明:本文为博主原创文章,转载请附上博文链接!

发布了18 篇原创文章 · 获赞 1 · 访问量 7021

猜你喜欢

转载自blog.csdn.net/weixin_42188216/article/details/83901147
今日推荐