Skip to content

Instantly share code, notes, and snippets.

@matthew-inamdar
Created December 3, 2018 15:16
Show Gist options
  • Save matthew-inamdar/96dbc57da9372b416374158367e40f59 to your computer and use it in GitHub Desktop.
Save matthew-inamdar/96dbc57da9372b416374158367e40f59 to your computer and use it in GitHub Desktop.
Parse a CSV string to an array and vice versa
<?php
/**
* @param string $content
* @return array
*/
function csv_to_array(string $content): array
{
$rows = str_getcsv($content, "\n");
foreach ($rows as &$row) {
$row = str_getcsv($row);
}
return $rows;
}
/**
* @see https://coderwall.com/p/zvzwwa/array-to-comma-separated-string-in-php For source of function
* @param array $data
* @return string
*/
function array_to_csv(array $data): string
{
// Generate CSV data from array.
$fh = fopen('php://temp', 'rw');
// Write out the data.
foreach ($data as $row) {
fputcsv($fh, $row);
}
rewind($fh);
$csv = stream_get_contents($fh);
fclose($fh);
return $csv;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment