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

 
 
Powered by Wordpress and MySQL. Theme by Shlomi Noach, openark.org