Created
September 12, 2012 14:35
-
-
Save sepehr/3707031 to your computer and use it in GitHub Desktop.
PHP: Parse CSV into Keyed Array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Parses CSV file into an associative array with the first row as field names. | |
* | |
* @param string $filepath Path to readable CSV file. | |
* @param array $options Parse options (eol, delimiter, enclosure, escape, to_object). | |
* | |
* @return array Associative array of parsed CSV file. | |
*/ | |
function csv_parse($filepath, $options = array()) | |
{ | |
if ( ! is_readable($filepath)) | |
{ | |
return FALSE; | |
} | |
// Merge default options | |
$options = array_merge(array( | |
'eol' => "\n", | |
'delimiter' => ',', | |
'enclosure' => '"', | |
'escape' => '\\', | |
'to_object' => FALSE, | |
), $options); | |
// Read file, explode into lines | |
$string = file_get_contents($filepath); | |
$lines = explode($options['eol'], $string); | |
// Read the first row, consider as field names | |
$header = array_map('trim', explode($options['delimiter'], array_shift($lines))); | |
// Build the associative array | |
$csv = array(); | |
foreach ($lines as $line) | |
{ | |
// Skip if empty | |
if (empty($line)) | |
{ | |
continue; | |
} | |
// Explode the line | |
$fields = str_getcsv($line, $options['delimiter'], $options['enclosure'], $options['escape']); | |
// Initialize the line array/object | |
$temp = $options['to_object'] ? new stdClass : array(); | |
foreach ($header as $index => $key) | |
{ | |
$options['to_object'] | |
? $temp->{trim($key)} = trim($fields[$index]) | |
: $temp[trim($key)] = trim($fields[$index]); | |
} | |
$csv[] = $temp; | |
} | |
return $csv; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment