PHP 将MySQL数据导出csv
1.查询数据
// 假设得到的数据格式如下
$result = array(
array(
"orderid" = "1110111",
"shopid" = "202302323",
),
array(
"orderid" = "1110111",
"shopid" = "202302323",
)
);
2.组装数据
$string = "订单ID,店铺ID\n";
foreach($result as $key => $value) {
$string .= $value['orderid'] . ',' . "\t" . $value['shopid'] . "\t\n";
}
说明:
- 字段值之间用英文 ","隔开;
- 遇到数字字符串时结尾加 "\t",否则长度超过12位会被转为科学计数法形式;
3. 改变编码格式
$string =iconv('utf-8', 'gb2312', $string);
最好将编码转一下,否则execl 下中文乱码
4. 导出csv
$filename = date('Y-m-d').'.csv';
header("Content-type:text/csv");
header("Content-Disposition:attachment;filename=".$filename);
header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
header('Expires:0');
header('Pragma:public');
echo $string;