Created
December 3, 2018 15:16
-
-
Save matthew-inamdar/96dbc57da9372b416374158367e40f59 to your computer and use it in GitHub Desktop.
Parse a CSV string to an array and vice versa
This file contains hidden or 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 | |
/** | |
* @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