Skip to content

Instantly share code, notes, and snippets.

@giventofly
Created January 17, 2021 23:38
Show Gist options
  • Save giventofly/eed09723f701ebbd985dec3b60cb0561 to your computer and use it in GitHub Desktop.
Save giventofly/eed09723f701ebbd985dec3b60cb0561 to your computer and use it in GitHub Desktop.
string csv to array
<?php
/**
* Receives CSV string and returns as an array.
*/
function csv_to_array($csv, $delimiter=',', $header_line=true) {
// CSV from external sources may have Unix or DOS line endings. str_getcsv()
// requires that the "delimiter" be one character only, so we don't want
// to pass the DOS line ending \r\n to that function. So first we ensure
// that we have Unix line endings only.
$csv = str_replace("\r\n", "\n", $csv);
// Read the CSV lines into a numerically indexed array. Use str_getcsv(),
// rather than splitting on all linebreaks, as fields may themselves contain
// linebreaks.
$all_lines = str_getcsv($csv, "\n");
if (!$all_lines) {
return false;
}
$csv = array_map(
function(&$line) use ($delimiter) {
return str_getcsv($line, $delimiter);
},
$all_lines
);
if ($header_line) {
// Use the first row's values as keys for all other rows.
array_walk(
$csv,
function(&$a) use ($csv) {
$a = array_combine($csv[0], $a);
}
);
// Remove column header row.
array_shift($csv);
}
return $csv;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment