Return to Snippet

Revision: 59150
at August 21, 2012 04:53 by TimoZachi


Initial Code
<?php
class CSVData
{
	public $colDelimiter = ';';
	
	public function __construct($colDelimiter = ';')
	{
		$this->colDelimiter = $colDelimiter;
	}
	/**
	 * Converts an array of data to CSV format.
	 * 
	 * @param string $head The CSV header. Example: array('User id', 'User Name', 'User Email');
	 * @param string $data The CSV data. Example:
	 * array(
	 *   array(1, 'John',   '[email protected]'  ),
	 *   array(2, 'Andrew', '[email protected]'),
	 *   array(3, 'Ana',    '[email protected]'  )
	 * );
	 * @return string The Proper formatted CSV string
	 */
	public function arrayToCSV($head, $data)
	{
		$csv = '';
		array_unshift($data, $head);
		foreach($data as $d) $csv .= implode($this->colDelimiter, array_map(array($this, '_quoteStr'), $d)) . "\n";
		return $csv;
	}
	/**
	 * Downloads CSV string to client as a file
	 * @param string $csv A properly formatted CSV string
	 * @param string $fileName Name of the file to be downloaded. Example: 'mycsv'
	 * @param bool $noCache [Optional] If true, headers will be sent to prevent
	 * browser caching of the CSV.
	 */
	public function downloadCSV($csv, $fileName, $noCache = false)
	{
		$len = strlen($csv);
		
		if($noCache) $this->_noCacheHeaders();
		header("Content-Type: text/csv");
		header("Content-Disposition: attachment; filename=\"{$fileName}.csv\";");
		header('Content-Transfer-Encoding: binary');
		header("Content-Length: {$len}");
		echo $csv;
	}
	/**
	 * Saves a CSV string as a CSV file in the server
	 * @param string $csv A properly formatted CSV string
	 * @param string $path Where to save the file. Example: archives/csv/.
	 * Notice the / at the end of the path.
	 * @param string $fileName Name of the file to be saved. Example: 'mycsv'
	 */
	public function saveCSV($csv, $path, $fileName)
	{
		$handle = fopen($path . $fileName . '.csv', 'w');
		if($handle === false) throw new Exception(
			'Could not create file: ' . $path . $fileName . '.csv'
		);
		fwrite($handle, $csv);
		fclose($handle);
	}
	//////////////////////////////////////////////////////////////////////////////////////////
	//PRIVATES
	//////////////////////////////////////////////////////////////////////////////////////////
	/** Quotes CSV column if necessary. */
	private function _quoteStr($str)
	{
		if(strpos($str, '"') !== false || strpos($str, $this->colDelimiter) !== false)
		{
			$str = '"' . str_replace('"', '""', $str) . '"';
		}
		return $str;
	}
	/** Sends no caching headers to browser. */
	private function _noCacheHeaders()
	{
		header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); //Date in the past
		header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); //Now
		header('Cache-Control: no-store, no-cache, must-revalidate');
		header('Cache-Control: post-check=0, pre-check=0', false);
		header('Pragma: no-cache');
	}
}

//Usage of class
$head = array('User id', 'User Name', 'User Email'); //The head will probably be static
$data = array( //This data could be grabbed from a database
	array(1,  'John',      '[email protected]'      ),
	array(2,  'Andrew',    '[email protected]'    ),
	array(3,  'Ana',       '[email protected]'      ),
	array(4,  'Carlos',    '[email protected]'   ),
	array(5,  'Christina', '[email protected]'),
	array(6,  'Zed',       '[email protected]'      ),
	array(7,  'Nina',      '[email protected]'     ),
	array(8,  'Gabriela',  '[email protected]' ),
	array(9,  'Joseph',    '[email protected]'   ),
	array(10, 'Ariel',     '[email protected]'    )
);

$csv = new CSVData(); //Create a new instance
//Transform the array to CSV string
$csvStr = $csv->arrayToCSV($head, $data);
//Download CSV, the browser will prompt
//the user to download the file
$csv->downloadCSV($csvStr, 'users', true);
//Whrite csv data to the server
$csv->saveCSV($csvStr, 'archives/csv/', 'users');
?>

Initial URL


Initial Description
Class that convert arrays to csv format, downloads CSV files and saves to disk on server.

Initial Title
CSV handler class

Initial Tags
class, download, csv

Initial Language
PHP