Skip to content

Instantly share code, notes, and snippets.

Last active February 11, 2019 16:53
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
Read a CSV file and convert to JSON object
* 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;
foreach ($row as $index => $column_value) {
$result[$i -1][$column_names[$index]] = $column_value;
return json_encode($result);
$url = '';
echo csv2json($url);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment