php 导出csv文件实例

CSV是以逗号间隔的文本文件
开发中,导出功能经常会用到,当数据量比较大的时候,发现csv格式的效率要比xls的效率要高一些,以yii先开发为例,优化表格数据导出



public $filename;

//方法1:
public function export()
{
    set_time_limit(0);
    ini_set('memory_limit',500M);
    $this->filename = iconv('UTF-8','GBK','商品表'.date('Y-m-d',time()).'csv');

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

    $firset_row_array = [
        'product_id'=>iconv('UTF-8','GBK','商品序号'),
        'product_sn'=>iconv('UTF-8','GBK','商品货号'),
        'product_name'=>iconv('UTF-8','GBK','商品名称'),
        'product_price'=>iconv('UTF-8','GBK','商品价格'),
        'product_num'=>iconv('UTF-8','GBK','商品库存'),
    ];
    $fp = fopen('php://output','product');
    fputcsv($fp,$forst_row_array);

    $list_model = Product::find()
          ->select('product_id,product_sn,product_name,product_price,product_num')
          ->asArray();

    $i=0;
    $limit = 100;

    //注:此处yii查询使用each或者batch方式,比all()查询效率高
    foreach($list_model->each(100) as $val){
        $i++;
        if($i == $limit){  //刷新一下输出buffer,防止由于数据过多造成问题
            ob_flush();
            flush();
            $i=0;
        }
        item = [
            iconv('UTF-8','GBK',$val['product_id']),
            iconv('UTF-8','GBK',$val['product_sn']),
            iconv('UTF-8','GBK',$val['product_name']),
            iconv('UTF-8','GBK',$val['product_price']),
            iconv('UTF-8','GBK',$val['product_num']),
        ];
        fputcsv = ($fp,$item);
        unset($item);
    }

    fclose($fp);
}


//方法2:
public function export()
{
    $this->filename = iconv('UTF-8','GBK','商品表'.date('Y-m-d',time()).'csv');
    header('Content-Type:application/octet-stream');
    header('Content-Disposition:attachment;filename='.$this->filename);

    $firset_row_array = ['商品序号','商品货号','商品名称','商品价格','商品库存'];
    echo iconv('utf-8','gbk//TRANSLIT','"'.implode('","', $first_row_array)."\"\n");

    $list_model = Product::find()
          ->select('product_id,product_sn,product_name,product_price,product_num')
          ->asArray();

    foreach($list_model->each(100) as $val){
        $item = array();
        $item[] = $val['product_id'];
        $item[] = $val['product_sn'];
        $item[] = $val['product_name'];
        $item[] = $val['product_price'];
        $item[] = $val['product_num'];
        echo iconv('utf-8','gbk//TRANSLIT','"'.implode('","', $item)."\"\n");
    }

}

你可能感兴趣的:(PHP)