【发布时间】:2020-01-17 03:57:40
【问题描述】:
我试图弄清楚为什么此代码不适用于 Google Apps Script 网络应用 URL,但它可以用于随机 Web API URL?
第一个代码块从虚拟 API 获取数据。第二个代码块不会从 Google Apps 脚本网络应用 URL 中返回任何内容。代码中唯一的区别是 $url 变量值。
GAS 应用程序设置为 Web 应用程序,因此任何人,即使是匿名的,都可以访问它(下面的屏幕截图)。如果我直接访问 GAS url GAS Output,它会返回 JSON。
Google Apps 脚本代码在下面的第三个代码块中。
有什么想法吗?
感谢 Tanaike,问题解决了!!工作代码粘贴在问题的底部。
第一个代码块
<?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);
?>
第二个代码块
<?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);
?>
第一个代码块:GAS 代码
function doGet(e) {
var data = {
status: 'success',
dataSet: 'Some Info'
};
var output = JSON.stringify(data);
return ContentService.createTextOutput(output).setMimeType(ContentService.MimeType.JSON);
}
工作代码,谢谢 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);
?>
【问题讨论】:
标签: php rest api curl google-apps-script