PHP快速导出csv

//快速导出csv

$file = '国家简码' . time(). '.csv';

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

header("Content-Disposition:attachment;filename=".$file);

header('Cache-Control:must-revalidate,post-check=0,pre-check=0');

header('Expires:0');

header('Pragma:public');

$top = "序号(ID),二位简码,国家英文名,国家中文名,创建人,创建时间,状态\n";

echo mb_convert_encoding($top, "CP936", "UTF-8");      //cp936就是指系统里第936号编码格式,也就是GB2312

$sql = "select * from country";

$data = db()->fetchAll($sql);

if (!empty($data)) {

    foreach ($data as $key=>$item) {

        $str = trim($item['id']) . ",";

        $str .= trim($item['country_acronym_two']) . ",";

        $str .= trim($item['country_name_en']) . ",";

        $str .= trim($item['country_name_cn']) . ",";

        $str .= $item['create_user'] . ",";

        $str .= $item['create_time'] . ",";

        $str .= ($item['status'] == 1) ? '启用,' : '禁用,';

        $str .= "\n";

        echo mb_convert_encoding($str, "CP936", "UTF-8");

        unset($str);

    }

}





//快速导出csv到服务器

$sql = "select * from teble_name";

$data = db()->fetchAll($sql);

if (!empty($data)) {

    $header = array_keys($data['0']);      //头部列

    $fp = fopen('f:/test.csv', 'w');

    fputcsv($fp,$header);

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

        fputcsv($fp, array_values($val));  //数据列

    }

    fclose($fp);

}

echo "数据导出完毕\r\n";

你可能感兴趣的:(PHP快速导出csv)