Skip to content

Instantly share code, notes, and snippets.

@ur92
Forked from robflaherty/csv-to-json.php
Last active October 4, 2021 15:42
Show Gist options
  • Save ur92/d4500756fa215e776a2a to your computer and use it in GitHub Desktop.
Save ur92/d4500756fa215e776a2a to your computer and use it in GitHub Desktop.
Convert CSV to JSON
<?php
/*
* Converts CSV to JSON
* Example uses Google Spreadsheet CSV feed
* csvToArray function I think I found on php.net
*/
header('Content-type: application/json');
// Set your CSV feed
$feed = 'https://docs.google.com/spreadsheet/pub?hl=en_US&hl=en_US&key=0Akse3y5kCOR8dEh6cWRYWDVlWmN0TEdfRkZ3dkkzdGc&single=true&gid=0&output=csv';
// Arrays we'll use later
$keys = array();
$newArray = array();
// Convert CSV into associative array
$data = array_map('str_getcsv', file($feed));
// Set number of elements (minus 1 because we shift off the first row)
$count = count($data) - 1;
//Use first row for names
$labels = array_shift($data);
foreach ($labels as $label) {
$keys[] = $label;
}
// Add Ids, just in case we want them later
$keys[] = 'id';
for ($i = 0; $i < $count; $i++) {
$data[$i][] = $i;
}
// Bring it all together
for ($j = 0; $j < $count; $j++) {
$d = array_combine($keys, $data[$j]);
$newArray[$j] = $d;
}
// Print it out as JSON
echo json_encode($newArray);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment