【问题标题】:How to use PHP's 'json_decode' on the new Google Calendar v3 API results?如何在新的 Google Calendar v3 API 结果中使用 PHP 的“json_decode”?
【发布时间】:2015-03-19 20:00:42
【问题描述】:

这是我的代码:

$gcal_path = "https://www.googleapis.com/calendar/v3/calendars/".$gcal_url_encoded_id."/events?maxResults=".$max_Results."&orderBy=startTime&singleEvents=true&timeMax=".$time_Max."&timeMin=".$time_Min."&key=".$api_key;

$feed = json_decode(html_entity_decode(trim(file_get_contents($gcal_path))));

我的脚本中已经准备好其他所有内容,包括解析来自json_decode 的数据。问题是$feed 不包含任何数据。

但是,我已经使用 AJAX 解析的 JavaScript 实现测试了 $gcal_path 变量/链接(例如 xmlhttp.open("GET","<?php echo $gcal_path ?>",true);。它会吐出所有正确的 JSON 数据。

那么,为什么 PHP 变量是空的?我做错了什么?

额外信息:另外,在结果中我注意到了这个"etag": "\"1576214503014905\""(出于安全目的,该数字已更改)。

如何处理那些转义的引号,是否会不可避免地影响json_decode函数调用和$feed的结果?

请帮忙。

【问题讨论】:

  • 使用 java 脚本发出 GET 请求,因此您可以获取结果。但是在 php 中,您并没有发送 HTTP 请求。为此更改如下代码:json_decode(html_entity_decode(trim(http_get($gcal_path))));为此,您必须安装 PECL。检查此链接php.net/manual/en/function.http-get.php。 file_get_contents 不是 http_request
  • 您有关于在 cPanel 中安装 PECL 的任何信息吗?有没有其他方法可以使用大多数 PHP 5.4 实现的标准扩展和托管帐户来做到这一点?
  • 那么,如果你只是var_dump(file_get_contents($gcal_path),你会得到什么?您可能没有在服务器上启用fopen_wrappers,在这种情况下,file_get_contents() 无法使用 URL。您需要改用 cURL 或其他 HTTP 库。不要担心报价转义。 json_decode() 应该为你默认。
  • 在 phpinfo.php 中将 allow_url_fopen 设置为 on
  • <?php $feed = file_get_contents($gcal_path); ?><script type="text/javascript">/* <?php echo var_dump($feed); ?> */</script> 返回:bool(false);

标签: javascript php json google-api google-calendar-api


【解决方案1】:

解决了!

这是工作代码:

$gcal_path = "https://www.googleapis.com/calendar/v3/calendars/".$gcal_url_encoded_id."/events?maxResults=".$max_Results."&orderBy=startTime&singleEvents=true&timeMax=".$time_Max."&timeMin=".$time_Min."&key=".$api_key;

// Get cURL resource.
$curl = curl_init();

// Set some options - we are passing in a user-agent too here.
curl_setopt_array($curl, array(
    CURLOPT_RETURNTRANSFER => 1,
    CURLOPT_URL => $gcal_path,
    CURLOPT_USERAGENT => '{enter a user-agent string ( some can be found at: http://www.useragentstring.com/pages/Chrome/) here, without the curly braces} ',
    CURLOPT_REFERER => '{enter the referrer URL, that is allowed to get the calendar JSON, here, without the curly braces}'
));
// Send the request & save response to $resp.
$resp = curl_exec($curl);
// Close request to clear up some resources.
curl_close($curl);

// Populate the '$feed' variable with decoded JSON data.
$feed = json_decode($resp); 

感谢@SGC 为我指明了正确的方向!

非常感谢您!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-21
    • 1970-01-01
    • 2015-02-01
    • 2013-04-10
    • 2013-12-03
    • 1970-01-01
    相关资源
    最近更新 更多