-
-
Save mystix/62a1f8529addecb82807 to your computer and use it in GitHub Desktop.
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 | |
/** | |
* Convert a comma separated file into an associated array. | |
* The first row should contain the array keys. | |
* | |
* Example: | |
* | |
* @param string $filename Path to the CSV file | |
* @param string $delimiter The separator used in the file | |
* @param boolean $asHash Use header row as keys in the returned array | |
* @return array | |
* @link http://gist.github.com/385876 | |
* @author Jay Williams <http://myd3.com/> | |
* @copyright Copyright (c) 2010, Jay Williams | |
* @license http://www.opensource.org/licenses/mit-license.php MIT License | |
*/ | |
function csv_to_array($filename = '', $delimiter = ',', $asHash = true) { | |
if (!(is_readable($filename) || (($status = get_headers($filename)) && strpos($status[0], '200')))) { | |
return FALSE; | |
} | |
$header = NULL; | |
$data = array(); | |
if (($handle = fopen($filename, 'r')) !== FALSE) { | |
if ($asHash) { | |
while ($row = fgetcsv($handle, 0, $delimiter)) { | |
if (!$header) { | |
$header = $row; | |
} else { | |
$data[] = array_combine($header, $row); | |
} | |
} | |
} else { | |
while ($row = fgetcsv($handle, 0, $delimiter)) { | |
$data[] = $row; | |
} | |
} | |
fclose($handle); | |
} | |
return $data; | |
} | |
/** | |
* Example | |
*/ | |
print_r(csv_to_array('example.csv')); |
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
name | number | |
---|---|---|
Lorem | 11 | |
ipsum | 22 |
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
Array | |
( | |
[0] => Array | |
( | |
[name] => Lorem | |
[number] => 11 | |
) | |
[1] => Array | |
( | |
[name] => ipsum | |
[number] => 22 | |
) | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for providing this update to the csv_to_array() function. I've just updated my code to this and all works great!
One suggestion on your code is to replace:
$header = $row;
with:
$header = array_map('trim', $row);
I've been racking my brain trying to figure out how to trim the header row but then found the answer on the original gist!