Export to CSV in PHP

CSV (Comma Separated Values) is a text-based format, used by Microsoft Excel to exchange table information.

Here I will present you with a helper class for performing CSV export operation. The class exposes two static methods: * tableToCSV * downloadCSV

 
/**
 * Helper utilities for CSV export.
 * @author Ivan Georgiev
 */
class ig_helper_CSV {
 
	/**
	 * Convert a 2D array to a CSV-string.
	 *
	 * @param array $table
	 * @return string
	 */
	function tableToCSV($table) {
		$out = '';
		foreach(array_keys($table) as $rowIndex) {
			$sep = '';
			foreach(array_keys($table[$rowIndex]) as $colIndex) {
				$out .= $sep . '"' . addcslashes($table[$rowIndex][$colIndex], '"') . '"';
				if ($sep == '') $sep = ',';
			}
			$out .= "\n";
		}
		return $out;
	}
 
	/**
	 * Convert a 2D array to a CSV and send it
	 * to output for download.
	 *
	 * @param array $table
	 * @param string $fileName
	 */
	function downloadCSV($table, $fileName=null) {
		if ( is_null($fileName) ) {
			$fileName = uniqid('export_') . '.csv';
		}
		header('Content-type: application/csv');
		header('Content-Disposition: attachment; filename="' . $fileName . '"');
		print ig_helper_ExportCSV::tableToCSV($table);
	}
}

The following example shows how you can use the CSV helper to download data.

// Define data
$dataTable = array(
	// Row 1
	array('Hello', 'world', '!'),
	// Row 2
	array(5, 5, 1)
	);
// Send result to the user as a file with name 'char_count.csv'
ig_helper_ExportCSV::downloadCSV($dataTable, 'char_count.csv');

An array with rows is created first. The first row contains three strings and the second row, three numbers, representing the number of characters in each word from the first row.

Than the downloadCSV metod is invoked to convert the array to a string and send it to the user as a file download.

 
php/exportcsv.txt · Last modified: 2009/10/31 23:36 (external edit)
 
Recent changes RSS feed Creative Commons License Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki