<?php
namespace App\Library\lib;
class CsvLib
{
/**
* 【构造函数】
*
*/
public function __construct() {
}
/**
* 导出csv
* @param $data
*
* $data示例:
* $data = [
* 'xlsTitle' => [
* 'RFID', '商品名称', '单位', '入仓时间', '进货价', '零售价', '状态'
* ],
* 'xlsName' => '已贴标库存',
* 'xlsList' => $xlsList
* ];
*
* $data['xlsTitle'] : 表头
* $data['xlsName'] : 文件名称
* $data['xlsList'] : 表数据
*/
public static function export($data)
{
$xlsTitle = $data['xlsTitle'];
$arrayKeys = array_keys($xlsTitle);
$xlsName = $data['xlsName'];
$xlsList = $data['xlsList'];
// 头部
$string = '';
foreach ($xlsTitle as $key => $val) {
$xlsTitle[$key] = iconv('utf-8', 'gb2312', $val);
}
$string .= implode(',', $xlsTitle) . "\n";
// 内容
foreach ($xlsList as $key => $value) {
$exportData = [];
foreach ($arrayKeys as $k) {
$value = array_values($value);
$exportData[$k] = addslashes(iconv('utf-8', 'GBK//IGNORE', str_replace(',', ', ', $value[$k])));
}
$string .= implode(',', $exportData) . "\n";
}
$filename = $xlsName . date('Y-m-d H:i:s') . '.csv';
header("Content-type:text/csv");
header("Content-Disposition:attachment;filename=" . $filename);
header("Cache-Controller:must-revalidate,post-check=0,pre-check=0");
header('Expires:0');
echo $string;
}
}