Skip to content

Instantly share code, notes, and snippets.

@micah1701
Last active Feb 11, 2019
Embed
What would you like to do?
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