欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

laravel 封装公共的导出方法(前后端分离)

程序员文章站 2024-03-20 21:01:46
...
	/*
	*$csvName 文件名 string
	*$head 表头	  array
	*$data 数据	 array
	*$catalog 子目录
	*/
public function DownCsv($csvName = '',$head = [],$data = [],$catalog = 'csv/')
    {
        $path = '路径'.$catalog;
        $temp = '';
        $filename = $this->utfToGbk($csvName);
        $fileData = $this->utfToGbk(implode(",",$head)) . "\n";

        if(count($list) == count($list,1)){
            for ($i=0; $i<=count($list)-1; $i++){
                $temp .= $list[$i] . ','.'' ;
            }
            $temp = substr($temp,0,-1);
            $fileData .= $this->utfToGbk($temp) . "\n";
        }else{
            foreach ($list as $key => $value) {
                $temp = implode(",",$value);
                $temp = str_replace("\n", "", $temp);
                $fileData .= $this->utfToGbk($temp) . "\n";
            }
        }
        $filePath =  $path . $filename.'.csv';
        
        //返回url给前端
        if(file_put_contents($filePath, $fileData)){
            return ['url' => env('URL').$catalog.$filename.'.csv'];
        }else{
            return ['url' => ''];
        }
    }

    public function utfToGbk($data)
    {
        return iconv('utf-8', 'GBK//TRANSLIT//IGNORE', $data);
    }
相关标签: laravel