Skip to content

Instantly share code, notes, and snippets.

@berteh
Forked from jaywilliams/csv_to_array.php
Last active November 21, 2017 03:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save berteh/5418706 to your computer and use it in GitHub Desktop.
Save berteh/5418706 to your computer and use it in GitHub Desktop.
<?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
* @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=',')
{
if(!file_exists($filename) || !is_readable($filename))
return FALSE;
$header = NULL;
$data = array();
if (($handle = fopen($filename, 'r')) !== FALSE)
{
while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
{
if(!$header)
$header = $row;
else
$data[] = array_combine($header, $row);
}
fclose($handle);
}
return $data;
}
/**
* Convert a comma separated string into an associated array.
* The first row should contain the array keys.
*
* Example:
*
* @param string $input CSV data
* @param string $delimiter The separator used in the file
* @return array
* @link http://gist.github.com/5418706/
* @author Berteh <https://gist.github.com/berteh>
* @copyright Copyright (c) 2013, Berteh
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
function strcsv_to_array($input, $delimiter=',', $enclosure = '"', $escape = "\\") {
$header = NULL;
$data = array();
$fp = fopen("php://memory", 'r+');
fputs($fp, $input);
rewind($fp);
while (($row = fgetcsv($fp, 0, $delimiter, $enclosure, $escape)) !== FALSE) {
if(!$header)
$header = $row;
else
$data[] = array_combine($header, $row);
}
fclose($fp);
return $data;
}
/**
* Example
*/
print_r(csv_to_array('example.csv'));
print_r(strcsv_to_array("\"name\", \"number\"\n\"Lorem\", 88\n\"ipsum\", 99"));
?>
name number
Lorem 11
ipsum 22
Array
(
[0] => Array
(
[name] => Lorem
[number] => 11
)
[1] => Array
(
[name] => ipsum
[number] => 22
)
)
Array
(
[0] => Array
(
[name] => Lorem
[number] => 88
)
[1] => Array
(
[name] => ipsum
[number] => 99
)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment