Skip to content

Instantly share code, notes, and snippets.

@sepehr
Created September 12, 2012 14:35
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sepehr/3707031 to your computer and use it in GitHub Desktop.
Save sepehr/3707031 to your computer and use it in GitHub Desktop.
PHP: Parse CSV into Keyed Array
<?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