无法使用file_get_contents工作

时间:2011-05-28 10:39:39

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

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

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

现在当我 var_dump 时,我得到null。我确实试图转到网址https://graph.facebook.com/me?access_token=ACCESS_TOKEN&fields=id,name,picture。它显示了名称和photourl。

我感谢任何帮助。

4 个答案:

答案 0 :(得分:2)

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

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(已记录完毕)。

希望有所帮助!

答案 1 :(得分:1)

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

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

如果没有收到任何错误消息,则可能会阻止使用PHP user_agent进行访问。还有另一个php.ini设置。另外,请尝试curl

答案 2 :(得分:0)

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

我发现file_get_contents()仅在http响应为200时正常工作。

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

使用不正确的access_token点击Facebook API会返回400。

示例:

file_get_contents()与'http://www.google.co.uk'有效,来自谷歌的http回复为200

带有'http://www.google.co.uk/me'的file_get_contents()为空,来自Google的http回复为404

答案 3 :(得分:0)

 //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));
相关问题