其他分享
首页 > 其他分享> > laravel 封装公共的导出方法(前后端分离)

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

作者:互联网

	/*
	*$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,utfToGbk,封装,temp,list,导出,catalog,fileData,data
来源: https://blog.csdn.net/qq_48368649/article/details/113525662