<?php
class Array2csv{
/*
*@var string $ext 扩展名
*/
private $ext = 'csv';
/**
* @desc构造方法
* @param string $filename 要输出的文件名
* @param string $ext 扩展名
*/
public function __construct($filename,$ext=null){
ob_start();
header("Content-type: text/html;charset=utf-8");
header("Content-type: application/x-csv");
if(PHP_SAPI == 'cli') echo "CLI模式下不能导出csv文件r";
$this->ext = $ext === null ? $this->ext : $ext;
header("Content-Disposition: attachment;filename=".$filename.".".$this->ext);
ob_flush();
return $this;
}
/**
* @desc 打印excel标题
* @param array $title 要输出的标题行
* @param object Array2csv 对象本身
*/
public function title($title){
$title = implode(",", $title);
echo $title."n";
return $this;
}
/**
* @desc 打印一行excel内容
* @param array $body 要输出的内容
* @param object Array2csv 对象本身
*/
public function body($body){
if(!is_array($body) || empty($body)) {
return false;
}
$body = implode(",", $body);
echo $body."n";
return $this;
}
/**
* @desc 打印多行excel内容
* @param array $bodyArr 要输出的多行内容
* @param object Array2csv 对象本身
*/
public function multiBody($bodyArr){
if(!is_array($bodyArr) || empty($bodyArr)) return false;
foreach ($bodyArr as $key => $value) {
if(is_array($value)){
$value = implode(",", $value);
echo $value."n";
}
}
return $this;
}
}
$test = new Array2csv('test');
$arr = array(
array('luluyrt@163.com','奔跑的Man1','奔跑的userman'),
array('luluyrt@163.com','奔跑的Man2','奔跑的userman'),
array('luluyrt@163.com','奔跑的Man3','奔跑的userman'),
array('luluyrt@163.com','奔跑的Man4','奔跑的userman'),
array('luluyrt@163.com','奔跑的Man5','奔跑的userman'),
array('luluyrt@163.com','奔跑的Man6','奔跑的userman')
);
$test->title(array('测试','呵呵','哈哈'))->body(array('100,sadkl','sdsas','sdvsvdd分'))->multiBody($arr); |