檔案/發佈到網路/發佈工作表/取得公開資料連結/CSV PHP轉JSON
Getting JSON out of Google Spreadsheets
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(); // Function to convert CSV into associative array function csvToArray($file, $delimiter) { if (($handle = fopen($file, 'r')) !== FALSE) { $i = 0; while (($lineArray = fgetcsv($handle, 4000, $delimiter, '"')) !== FALSE) { for ($j = 0; $j < count($lineArray); $j++) { $arr[$i][$j] = $lineArray[$j]; } $i++; } fclose($handle); } return $arr; } // Do it $data = csvToArray($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);
沒有留言:
張貼留言
注意:只有此網誌的成員可以留言。