【问题标题】:Unable to file_get_contents to work无法 file_get_contents 工作
【发布时间】:2011-09-03 21:42:36
【问题描述】:

我正在使用 facebook graph api 来检索登录用户的信息。

$facebookdata = json_decode(file_get_contents('https://graph.facebook.com/me?access_token=' . $fb_accesstoken . '&fields=name,picture'),true);

现在当我 var_dump 我得到空值。我确实尝试转到 url https://graph.facebook.com/me?access_token=ACCESS_TOKEN&fields=id,name,picture。它显示名称和照片网址。

感谢您的帮助。

【问题讨论】:

  • 先尝试不使用json_decodevar_dump 并查看输出。 “调试”你的程序!
  • @ahmet 我也试过了,它显示 bool(false)。请帮助
  • 这意味着问题是它不工作。尝试获取其他页面(例如此页面)继续调试。

标签: php json facebook facebook-graph-api file-get-contents


【解决方案1】:
 //i had the same problem before.for some reason the server has a problem with file_get_contents and i used this function.try it instead
 /* gets the data from a URL */
 function get_myurl_data($url) {
$ch = curl_init();
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$data = curl_exec($ch);
curl_close($ch);
return $data;
 }
 $url = 'https://graph.facebook.com/me?access_token=' . $fb_accesstoken . '&fields=name,picture';
 $facebookdata = json_decode(get_myurl_data($url));

【讨论】:

    【解决方案2】:

    您应该确定您的请求返回的 http 响应代码。

    我发现 file_get_contents() 只在 http 响应为 200 时有效,OK。

    如果响应码为 404(页面未找到)、400(错误请求)等,则不返回字符串。

    使用不正确的 access_token 访问 Facebook API 会返回 400。

    例子:

    file_get_contents() 和 'http://www.google.co.uk' 有效,来自 google 的 http 响应是 200

    file_get_contents() with 'http://www.google.co.uk/me' 为 null,来自 google 的 http 响应为 404

    【讨论】:

      【解决方案3】:

      您可以使用更易于使用的 Facebook PHP SDK (see on github),而不是使用 file_get_contents

      require "facebook.php";
      $facebook = new Facebook(array(
          'appId'  => YOUR_APP_ID,
          'secret' => YOUR_APP_SECRET,
      ));
      
      $facebook->setAccessToken("...");
      
      $args['fields'] = "name,picture";
      $facebookdata = $facebook->api('/me', $args);
      

      如果您想查看获取用户访问令牌的流程,请查看example of the SDK(有据可查)。

      希望有帮助!

      【讨论】:

        【解决方案4】:

        检查您的php.ini 中是否启用了allow_url_fopen。否则适应,因为 file_get_contents 将无法从 http URL 读取。

        其次,提高你的error_reporting 等级。它应该告诉你的。

        如果您没有收到错误消息,则使用 PHP user_agent 的访问可能会被阻止。还有另一个 php.ini 设置。也可以试试curl

        【讨论】:

        • 我尝试将 file_get_contents 与其他 url 一起使用,效果很好。 allow_url_fopen 已启用。感谢您的帮助。
        • 还有 https 网址?你现在的错误级别是多少? $http_response_header 说什么?
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-08-28
        • 2015-02-21
        • 2011-12-09
        • 1970-01-01
        • 1970-01-01
        • 2011-04-24
        • 2013-07-11
        相关资源
        最近更新 更多