I'm trying to figure out why this code won't work with a Google Apps Script web app URL, but it will work with a random web API URL?
The 1st code block gets data from the dummy API. The second code block returns nothing from the Google Apps Script web app URL. The only difference in the code is the $url variable value.
The GAS App is set to Web App so anyone, even anonymous can access it (screenshot below). If I go directly to the GAS url GAS Output, it returns the JSON.
The Google Apps Script code is below in third code block.
Any ideas?
Problem solved thanks to Tanaike!! Working code pasted at the bottom of the question.
First Code Block
<?php
// Initiate curl session in a variable (resource)
$curl_handle = curl_init();
$url = "http://dummy.restapiexample.com/api/v1/employees";
// Set the curl URL option
curl_setopt($curl_handle, CURLOPT_URL, $url);
// This option will return data as a string instead of direct output
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, true);
// Execute curl & store data in a variable
$curl_data = curl_exec($curl_handle);
curl_close($curl_handle);
// Decode JSON into PHP array
$user_data = json_decode($curl_data);
// Print all data if needed
print_r($user_data);
?>
Second Code Block
<?php
// Initiate curl session in a variable (resource)
$curl_handle = curl_init();
$url = "https://script.google.com/macros/s/AKfycbyWSDzUyFa41fu_6QWP7h8ToklwWysGZsuSPaRnu649DmPNYG8/exec";
// Set the curl URL option
curl_setopt($curl_handle, CURLOPT_URL, $url);
// This option will return data as a string instead of direct output
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, true);
// Execute curl & store data in a variable
$curl_data = curl_exec($curl_handle);
curl_close($curl_handle);
// Decode JSON into PHP array
$user_data = json_decode($curl_data);
// Print all data if needed
print_r($user_data);
?>
First Code Block: GAS Code
function doGet(e) {
var data = {
status: 'success',
dataSet: 'Some Info'
};
var output = JSON.stringify(data);
return ContentService.createTextOutput(output).setMimeType(ContentService.MimeType.JSON);
}
Working Code, thank you Tanaike!!
<?php
// Initiate curl session in a variable (resource)
$curl_handle = curl_init();
$url = "https://script.google.com/macros/s/AKfycbyWSDzUyFa41fu_6QWP7h8ToklwWysGZsuSPaRnu649DmPNYG8/exec";
// Set the curl URL option
curl_setopt($curl_handle, CURLOPT_URL, $url);
// was an update from my stack overflow question.
curl_setopt($curl_handle, CURLOPT_FOLLOWLOCATION, true); //https://stackoverflow.com/questions/59780986/trouble-using-curl-with-google-apps-script-web-app-in-a-php-file/59781600#59781600
// This option will return data as a string instead of direct output
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, true);
// Execute curl & store data in a variable
$curl_data = curl_exec($curl_handle);
curl_close($curl_handle);
// Decode JSON into PHP array
$user_data = json_decode($curl_data);
// Print all data if needed
print_r($user_data);
?>