Skip to content

Instantly share code, notes, and snippets.

@micah1701
Last active February 11, 2019 16:53
Show Gist options
  • Save micah1701/22555ed0b95a57726f2443f2423d8bae to your computer and use it in GitHub Desktop.
Save micah1701/22555ed0b95a57726f2443f2423d8bae to your computer and use it in GitHub Desktop.
Read a CSV file and convert to JSON object
<?php
/**
* Read a CSV File an convert to JSON object
* Assumes first row is header data with column titles
* For Google Sheets, publish the sheet in csv format and use the provided URL
*/
function csv2json($url) {
$csv = file_get_contents($url);
$rows = array_map("str_getcsv", explode("\n", $csv));
$result = array();
$column_names = array();
foreach ($rows as $i => $row) {
if($i===0) {
foreach ($row as $index => $column_name) {
$column_names[$index] = $column_name;
}
continue;
}
foreach ($row as $index => $column_value) {
$result[$i -1][$column_names[$index]] = $column_value;
}
}
return json_encode($result);
}
//usage
$url = 'https://docs.google.com/spreadsheets/LINK/TO/YOUR-PUBLISHED-GOOGLE-DOCS-SHEET/pub?output=csv';
echo csv2json($url);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment