PHP CSV Writer

<?php
/**
 * Simple class to properly output CSV data to clients. PHP 5 has a built
 * in method to do the same for writing to files (fputcsv()), but many times
 * going right to the client is beneficial.
 *
 * @author Patrick WU
 */
class CSV_Writer {
    public $data = array();
    public $deliminator;
    function __construct($data, $deliminator = ",")
    {
        if (!is_array($data))
        {
            throw new Exception('CSV_Writer only accepts data as arrays');
        }
        $this->data = $data;
        $this->deliminator = $deliminator;
    }
    private function wrap_with_quotes($data)
    {
        $data = preg_replace('/"(.+)"/', '""$1""', $data);
        return sprintf('"%s"', $data);
    }
    public function output()
    {
        foreach ($this->data as $row)
        {
            $quoted_data = array_map(array('CSV_Writer', 'wrap_with_quotes'), $row);
            echo sprintf("%s\r\n", implode($this->deliminator, $quoted_data));
        }
    }
    public function headers($name)
    {
        header('Content-Type: application/csv');
        header("Content-disposition: attachment; filename={$name}.csv");
	//** record the csv file on the server side
        $file_store_folder = dirname(dirname(__FILE__)).DIRECTORY_SEPARATOR.'data';
        $file_path = $file_store_folder.DIRECTORY_SEPARATOR.$name.".csv";
        if(!is_dir($file_store_folder)){
              	@mkdir($file_store_folder, 0700);
         }
        if($this->data ){
              $fp = @fopen($file_path, 'w');
              foreach ($this->data as $line) {
                     fputcsv($fp, $line);
              }
              fclose($fp);
        }
    }
}
//$data = array(array("one","two","three"), array(4,5,6));
$data[] = array("one","two","three");
$data[] = array(4,5,6);
$csv = new CSV_Writer($data);
$csv->headers('test');
$csv->output();

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值