Skip to content

Instantly share code, notes, and snippets.

@PiotrKrzyzek
Last active October 10, 2019 19:25
Show Gist options
  • Save PiotrKrzyzek/effb866e6a89a8da9977f25e7c8ea9d6 to your computer and use it in GitHub Desktop.
Save PiotrKrzyzek/effb866e6a89a8da9977f25e7c8ea9d6 to your computer and use it in GitHub Desktop.
Flatten Airtables's JSON API response into one level per item (such as for use in single level inputs / csv file like inputs)
<?php
/* Setup some variables for us to use */
parse_str($_SERVER['QUERY_STRING'], $urls);
$returnJson = []; // This is the main returned object
// Save the app and board params for use
$app = $urls['app'];
$board = $urls['board'];
$api = "YOUR API KEY HERE";
// Unset them from the other params so we can cleanly use the rest of em for pulling data
unset($urls['app']);
unset($urls['board']);
$theURL = str_replace(' ', '%20', 'https://api.airtable.com/v0/' . $app . '/' . $board . '?api_key=' . $api . '&' . http_build_query($urls));
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $theURL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//Let's get the datas
$data = curl_exec($ch);
$result = json_decode($data);
// For each record returned
foreach ($result->records as $item) {
$flatFields = [];
// Flatten it's fields
foreach ($item->fields as $key => $val) {
$flatFields[$key] = $val;
}
// Combine it all into a 'flat' item for wpDataTables
$returnJson[] = array_merge(['id' => $item->id], $flatFields, ['createdTime' => $item->createdTime]);
}
/* Start and do output */
header('Content-type: application/json');
echo json_encode($returnJson);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment