How to read csv file into array ?

June 16, 2013
function csvToArray($file){
	$rows = array();
	$headers = array();
	if(file_exists($file) && is_readable($file)){
		$handle = fopen($file, 'r');
		while (!feof($handle) ) {
			$row = fgetcsv($handle, 10240);
			if(empty($headers))
				$headers = $row;
			else if(is_array($row))
				$rows[] = array_combine($headers, $row);
		}
		fclose($handle);
	} else {
		throw new Exception($file.' doesn`t exist or is not readable.');
	}
	return $rows;
}

Simple as that.

Suggestions or problems ? Write a comment.

tags: , ,
posted in how to ?, php by Ivan Gospodinow

Follow comments via the RSS Feed | Leave a comment | Trackback URL

Leave Your Comment


Warning: Use of undefined constant XML - assumed 'XML' (this will throw an Error in a future version of PHP) in /home/c2kblate/sites/ivangospodinow.com/wp-content/plugins/wp-syntaxhighlighter/wp-syntaxhighlighter.php on line 1048
 
Powered by Wordpress and MySQL. Theme by Shlomi Noach, openark.org