php导出cvs文件简单类/**
*@author/
*excelTool
*/
classCvsExport
{
publicstatic$readerObj;
publicstatic$charset='utf-8';
/**
*输出切换编码
*@param$output
*@returnfalse|string
*/
publicstaticfunctionexcelExportIconv($output)
{
returniconv(self::$charset,'GBK',$output);
}
/**
*文件保存
*@param$filePath
*@paramstring$title
*@paramarray$firstRow
*@paramarray$data
*@returnbool
*/
publicstaticfunctionsaveFile($filePath,$title='',$firstRow=[],$data=[]):bool
{
ob_start();
self::outputData($title,$firstRow,$data);
$content=ob_get_contents();
ob_clean();
if($fp=@fopen($filePath,'w+')){
if(fwrite($fp,$content)){
fclose($fp);
returntrue;
}
fclose($fp);
}
returnfalse;
}
/**
*数据输出
*@paramstring$title
*@paramarray$firstRow
*@paramarray$data
*/
protectedstaticfunctionoutputData($title='',$firstRow=[],$data=[])
{
if(!empty($title)){
echoself::excelExportIconv($title)."\t\n";
}
if(!empty($firstRow)&&is_array($firstRow)){
//输出第一行内容
foreach($firstRowas$first){
echoself::excelExportIconv($first)."\t";
}
echo"\n";
if(!empty($data)&&is_array($data)){
foreach($dataas$item){
foreach($firstRowas$_key=>$_val){
if(isset($item[$_key])){
echoself::excelExportIconv($item[$_key])."\t";
}else{
echoself::excelExportIconv('')."\t";
}
}
echo"\n";
}
}
}else{
if(!empty($data)&&is_array($data)){
foreach($dataas$item){
foreach($itemas$val){
echoself::excelExportIconv($val)."\t";
}
echo"\n";
}
echo"\n";
}
}
}
}
使用示例:$data=[
['id'=>'1','name'=>'名字1','title'=>'标题1'],
['id'=>'2','name'=>'名字2','title'=>'标题2'],
['id'=>'3','name'=>'名字3','title'=>'标题3'],
['id'=>'4','name'=>'名字4','title'=>'标题4'],
['id'=>'5','name'=>'名字5','title'=>'标题5'],
['id'=>'6','name'=>'名字6','title'=>'标题6'],
['id'=>'7','name'=>'名字7','title'=>'标题7'],
['id'=>'8','name'=>'名字8','title'=>'标题8'],
];
CvsExport::saveFile(
dirname(__FILE__).'/test.cvs',
'标题',
['id'=>'id','name'=>'名字','title'=>'内容'],
$data
);