<?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();