Skip to content

Instantly share code, notes, and snippets.

@tru2dagame
Created August 19, 2014 10:15
Show Gist options
  • Save tru2dagame/5fe8a8c40b59782dbbdd to your computer and use it in GitHub Desktop.
Save tru2dagame/5fe8a8c40b59782dbbdd to your computer and use it in GitHub Desktop.
php convert csv string to array
<?php
function convert_csv_string_to_array($csvstring) {
$lines = explode(PHP_EOL, current($csvstring));
$array = array();
foreach ($lines as $key => $line) {
if (substr(trim($line), -1) == ',') {
$line = substr(trim($line), 0, -1);
}
if ($key == 0) {
$head = str_getcsv($line);
} else {
$array[] = array_combine($head, str_getcsv($line));
}
}
return $array;
}
@bantya
Copy link

bantya commented Oct 21, 2016

On line 3: the code is $lines = explode(PHP_EOL, current($csvstring));
it should be $lines = explode(PHP_EOL, $csvstring); as current() expects array as an argument.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment