Skip to content

Instantly share code, notes, and snippets.

@leepettijohn
Last active January 10, 2022 16:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leepettijohn/619303ad7d47ee8f827321758b74fd83 to your computer and use it in GitHub Desktop.
Save leepettijohn/619303ad7d47ee8f827321758b74fd83 to your computer and use it in GitHub Desktop.
Airtable API call to create a button to download results in CSV format
<?php
function replaceSpace($string){
$string = str_replace('%20',' ',$string);
return str_replace(' ','+',$string);
}
// C.I.N.N. = Comment if not needed
// Find a copy of the js file here - https://github.com/Airtable/airtable.js/blob/master/build/airtable.browser.js
$ATJS = 'https://yoursite.com/wp-content/themes/Divi/js/airtable.js';
// Table and data variables
//Get baseid and apikey here - https://airtable.com/api
$baseid = '___baseid___'; //Required
$apikey = '___apikey___'; //Required
// tablename and view - one gets the value from the URL and the other is static
//$tablename = filter_var($_GET['___tablename___'],FILTER_SANITIZE_STRING); //Required 1
//$view = filter_var($_GET['___viewname___'],FILTER_SANITIZE_STRING); //Optional 1
$tablename = '___tablename___'; //Required 2
$view = '___viewname___'; //Optional 2
//$lookupfieldname = 'Parameter Group'; //Optional 1a C.I.N.N.
$lookupfieldvalue = filter_var($_GET['___lookupfieldvalue___'],FILTER_SANITIZE_STRING); //Optional 1b
//Use "start" and "end" in URL if needed
$startdate = filter_var($_GET['start'],FILTER_SANITIZE_STRING);
$enddate = filter_var($_GET['end'],FILTER_SANITIZE_STRING);
$startname = substr($startdate,0,10);
$endname = substr($enddate,0,10);
//$datefield = "Close Date"; //Optional C.I.N.N.
// Use if necessary but Airtable views can be sorted and will be reflected in results
//$sortfield = 'Order'; //Optional 2a
//$sortdirection = 'asc'; //Optional 2b
$maxrecords = ''; //Optional
$filename = $tablename;
if (!empty($lookupfieldname)){
$filename .= '---'.$lookupfieldname;
}
if (!empty($datefield)){
$filename .= '---'.$startname.'---'.$endname;
}
//$neededFields = ['Round Code','Start Date']; //Optional C.I.N.N.
// Modifies the users table name input to be used in a URL
$encodedtablename = str_replace(' ','%20',$tablename);
// All the extra variables in the URL
// See https://codepen.io/airtable/pen/rLKkYB for Encoder
/*
%7B = {
%7D = }
%3D = =
%22 = "
%28 = (
%29 = )
%2C = ,
*/
if (!empty($datefield) && !empty($lookupfieldname)){
$filtervar = "&filterByFormula=AND(Find(%22".replaceSpace($lookupfieldvalue)."%22%2C+%7B".replaceSpace($lookupfieldname)."%7D)%2CIS_AFTER(%7B".replaceSpace($datefield)."%7D%2C+DATETIME_PARSE('".$startdate."'))%2C+IS_BEFORE(%7B".replaceSpace($datefield)."%7D%2C+DATETIME_PARSE('".$enddate."')))";
}elseif (!empty($lookupfieldname)){
$filtervar = "&filterByFormula=AND(Find(%22".replaceSpace($lookupfieldvalue)."%22%2C+%7B".replaceSpace($lookupfieldname)."%7D))";
}elseif (!empty($datefield)){
$filtervar = "&filterByFormula=AND(IS_AFTER(%7B".replaceSpace($datefield)."%7D%2C+DATETIME_PARSE('".$startdate."'))%2C+IS_BEFORE(%7B".replaceSpace($datefield)."%7D%2C+DATETIME_PARSE('".$enddate."')))";
}
$filterview = '&view='.replaceSpace($view);
//$filtersort = '&sort%5B0%5D%5Bfield%5D='.replaceSpace($sortfield).'&sort%5B0%5D%5Bdirection%5D='.$sortdirection;
$filtermaxrecords = '&maxRecords='.$maxrecords;
// Logic to decide if needs to add variables
$filterurl = '';
if(!empty($lookupfieldname) || !empty($datefield)){$filterurl.=$filtervar;}
if(!empty($view)){$filterurl.=$filterview;}
//if(!empty($sortfield)){$filterurl.=$filtersort;}
if(!empty($maxrecords)){$filterurl.=$filtermaxrecords;}
if(!empty($fieldsneededarray)){$filterurl.=$filterfield;}
//Get results from AT
$starturl = 'https://api.airtable.com/v0/'.$baseid.'/'.$encodedtablename.'?api_key='.$apikey;
$ch = curl_init($starturl.$filterurl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json'
));
$result = curl_exec($ch);
$decoderesult = json_decode($result,true)['records'];
//print "<pre>";print_r($starturl.$filterurl);print "</pre>";
//print "<pre>";print_r($result);print "</pre>";
//print_r($result);
$reencoderesult = json_encode($decoderesult);
$csv_a = array();
$arrayheader = array();
foreach($decoderesult as $eachrecord){
foreach($eachrecord as $eachkey => $eachresult){
if ($eachkey == 'fields'){
$arrayrow = array();
$i = 0;
foreach($eachresult as $eachfieldkey => $eachfieldresult){
if (empty($neededFields) || in_array($eachfieldkey,$neededFields)){
if(strpos($eachfieldresult,',') >0){
$eachfieldresult = '"'.$eachfieldresult.'"';
}
if(strpos($eachfieldresult,"'") >0){
$eachfieldresult = str_replace("'",'`',$eachfieldresult);
}
if(strpos($eachfieldresult,'"') >0){
$eachfieldresult = str_replace('"','`',$eachfieldresult);
}
if(strpos($eachfieldresult,"#") >0){
$eachfieldresult = str_replace("#",':',$eachfieldresult);
}
if(strpos($eachfieldkey,"'") >0){
$eachfieldkey = str_replace("'",'`',$eachfieldkey);
}
if(strpos($eachfieldkey,'"') >0){
$eachfieldkey = str_replace('"','`',$eachfieldkey);
}
if(strpos($eachfieldkey,",") >0){
$eachfieldkey = str_replace(",",'',$eachfieldkey);
}
if(strpos($eachfieldkey,"#") >0){
$eachfieldkey = str_replace("#",':',$eachfieldkey);
}
$eachfieldkey = trim(preg_replace("/\r|\n/", '', $eachfieldkey));
if(is_array($eachfieldresult)){
$eachfieldresult = implode(' / ',$eachfieldresult);
}
$eachfieldresult = trim(preg_replace("/\r|\n/", '', $eachfieldresult));
if (!array_key_exists($eachfieldkey,$arrayheader)){
$newArray = array_slice($arrayheader, 0, $i+1, true) +
array($eachfieldkey => $eachfieldkey) +
array_slice($arrayheader, $i+1, NULL, true);
}
$arrayheader = $newArray;
$arrayrow[$eachfieldkey] = $eachfieldresult;
$i++;
}
}
$csv_a[] = $arrayrow;
}
}
}
//print_r($arrayheader);
$csv_string = implode(',',$arrayheader).'\n';
foreach($csv_a as $eachresponse){
$eachrowarray = array();
foreach($arrayheader as $eachheader){
if (array_key_exists($eachheader,$eachresponse)){
$eachrowarray[] = $eachresponse[$eachheader];
}else $eachrowarray[] = '';
}
$csv_string .= implode(',',$eachrowarray).'\n';
}
$final_csv_a = json_encode($csv_string);
//print "<pre>";print_r($csv_string);print "</pre>";
?>
<script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js'></script>
<script src="<?php echo $ATJS; ?>"></script>
<script>
function download_csv(){
var csv_string = '<?php echo $csv_string; ?>';
var hiddenElement = document.createElement('a');
hiddenElement.href = 'data:text/csv;charset=utf-8,' + encodeURI(csv_string);
hiddenElement.target = '_blank';
hiddenElement.download = '<?php echo $filename;?>.csv';
hiddenElement.click();
}
jQuery(document).ready(function($) {
});
</script>
<p>Table: <?php echo $tablename;?></p>
<?php if (!empty($lookupfieldname)){ ?>
<p>Field: <?php echo $lookupfieldname;?> </p>
<?php } ?>
<?php if (!empty($datefield)){ ?>
<p>Start Date: <?php echo $startname; ?></p>
<p>End Date: <?php echo $endname; ?></p>
<?php } ?>
<button onclick="download_csv()">Download CSV</button>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment