maxyudin

Google Spreadsheets to JSON

Jan 15th, 2012
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.28 KB | None | 0 0
  1. <?php
  2. /* http://www.ravelrumba.com/blog/json-google-spreadsheets/ */
  3.  
  4. header('Content-type: application/json');
  5.  
  6. // Set your CSV feed
  7. $feed = 'https://docs.google.com/spreadsheet/pub?hl=en_US&hl=en_US&key=0Akse3y5kCOR8dEh6cWRYWDVlWmN0TEdfRkZ3dkkzdGc&single=true&gid=0&output=csv';
  8.  
  9. // Arrays we'll use later
  10. $keys = array();
  11. $newArray = array();
  12.  
  13. // Function to convert CSV into associative array
  14. function csvToArray($file, $delimiter) {
  15. if ( ($handle = fopen($file, 'r') ) !== FALSE) {
  16.     $i = 0;
  17.     while (($lineArray = fgetcsv($handle, 4000, $delimiter, '"')) !== FALSE) {
  18.         for ($j = 0; $j < count($lineArray); $j++) {
  19.             $arr[$i][$j] = $lineArray[$j];
  20.         }
  21.         $i++;
  22.     }
  23.     fclose($handle);
  24. }
  25. return $arr;
  26. }
  27.  
  28. // Do it
  29. $data = csvToArray($feed, ',');
  30.  
  31. // Set number of elements (minus 1 because we shift off the first row)
  32. $count = count($data) - 1;
  33.  
  34. //Use first row for names
  35. $labels = array_shift($data);
  36.  
  37. foreach ($labels as $label) {
  38.     $keys[] = $label;
  39. }
  40.  
  41. // Add Ids, just in case we want them later
  42. $keys[] = 'id';
  43.  
  44. for ($i = 0; $i < $count; $i++) {
  45.     $data[$i][] = $i;
  46. }
  47.  
  48. // Bring it all together
  49. for ($j = 0; $j < $count; $j++) {
  50.     $d = array_combine($keys, $data[$j]);
  51.     $newArray[$j] = $d;
  52. }
  53.  
  54. // Print it out as JSON
  55. echo json_encode($newArray);
  56.  
  57. ?>
Add Comment
Please, Sign In to add comment