php csv数据导出

public function exportgood(){

        set_time_limit(0);

        ignore_user_abort(true);

        ini_set('memory_limit', '1024M');

        //查询出来的结果$data

        $arr_excelHeaderinfo = ['A'=>['35','商品ID','goods_id'],'B'=>['50','货号','goods_sn'],'C'=>['25','sku名称','sku_name'],'D'=>['30','sku编码','sku_code'],'E'=>['30','品牌','brand_name'],'F'=>['30','第三方货号','third_goods_number'],'G'=>['120','商品名称','goods_name'],'H'=>['50','商品型号','goods_model'],'I'=>['30','商品分类','cat_name'],'J'=>['30','供货商','suppliers_name'],'K'=>['35','库存数量','total_stocks'],'L'=>['10','可用库存','goods_number'],'M'=>['10','成本价','cost_price'],'N'=>['10','商品售价','shop_price'],'O'=>['25','市场价','market_price'],'P'=>['30','是否上下架','is_on_sale'],'q'=>['30','采购价','ammout'],'r'=>['30','含豆价','been_ammout']];

        $fileName = "运营商品数据".date("Ymd",time());

        $this->publicExportCsv($arr_excelHeaderinfo,$data,$fileName);

    }.


public function publicExportCsv($arr_excelHeaderinfo,$arr,$fileName){

        header('Access-Control-Allow-Origin:*');//允许所有来源访问

        $headArr = array();

        $fieldArr = array();

        foreach ($arr_excelHeaderinfo as $k => $v) {

            $headArr[]=$v[1];

            $fieldArr[]=$v[2];

        }

        $data = array();

        foreach ($arr as $key => $val) {

            foreach ($fieldArr as $dk => $dv) {

                if (in_array($dv, array('parent_order_sn','order_sn','add_time','pay_time','shipping_time','invoice_no','mobile','goods_sn','goods_sku_name','id_card_number','sku_code','goods_model','third_goods_number'))) {

                    $data[$key][] = "\xEF\xBB\xBF".$val[$dv];

                }else{

                    $data[$key][] = $val[$dv];

                }

            }

        }

        // $data=array(array("1","2","3"),array("11","22","33"),array("111","222","333")); //模拟表格数据

        /**导出api**/

        ini_set('memory_limit','1024M'); //设置程序运行的内存

        ini_set('max_execution_time',0); //设置程序的执行时间,0为无上限

        ob_end_clean();  //清除内存

        ob_start();

        header("Content-Type: text/csv");

        header("Content-Disposition:filename=".$fileName.'.csv');

        $fp=fopen('php://output','w');

        fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));

        fputcsv($fp,$headArr);

        $index = 0;

        foreach ($data as $item) {

            if($index==1000){ //每次写入1000条数据清除内存

                $index=0;

                ob_flush();//清除内存

                flush();

            }

            $index++;

            fputcsv($fp,$item);

        }

        ob_flush();

        flush();

        ob_end_clean();

        exit();

    }


实测可以导出2W+条数据,如果出现500请优化你的sql语句

你可能感兴趣的:(php csv数据导出)