<?php
namespace lib;
/**
 * exportCsv
 * @author HzqGhost admin@whiledo.com QQ:313143468
 * @version 1.2.0
 *
 */
class exportCsv
{
    protected $fp; //流
    protected $br; //换行符
    private $isoutput; //是否输出到客户端
	public function __construct($fp)
    {
        $this->fp = $fp;
        $this->br = "\r\n";
        //UTF8 csv文件头前需添加BOM，不然会是乱码
        fwrite($this->fp, chr(0xEF).chr(0xBB).chr(0xBF));
    }
	public function header(string $filename='')
    {
        $this->isoutput = true;
        if($filename==''){
            $filename = time().'.csv';
        }
        ob_end_clean();
        header('Content-Description: File Transfer');
        header("Content-type:application/vnd.ms-excel");
        header('Content-Disposition: attachment; filename='.$filename);
        ob_start();
    }

	public function bookBegin()
    {
        ;
    }
	public function bookEnd()
    {
        ;
    }

	public function sheetBegin(string $sheetName,array $headerRow=[],array $headerRowWidths=[])
    {
        if(!empty($headerRow)){
            fputcsv($this->fp, $headerRow);
        }
    }

	public function sheetEnd()
    {
        ;
    }

	public function append(array $row=[])
    {
        if($row){
            foreach($row as $k=>$cell){
                $row[$k] = $this->specialchars($cell);
            }
            fputcsv($this->fp, $row);
        }
        if($this->isoutput){
            ob_flush();
            flush();
        }
    }

    protected function specialchars(string $value){
        return str_replace(['&amp;','"'],['&','\"'],htmlspecialchars($value));
    }
}