【问题标题】:Getting Education with Facebook Graph API in PHP在 PHP 中使用 Facebook Graph API 获得教育
【发布时间】:2012-12-07 06:27:33
【问题描述】:

我正在尝试使用 stdclass 从 Facebook 的图形 API 获取教育信息。这是数组:

 "username": "blah",
   "education": [
      {
         "school": {
            "id": "[removed]",
            "name": "[removed]"
         },
         "year": {
            "id": "[removed]",
            "name": "[removed]"
         },
         "type": "High School"
      },
      {
         "school": {
            "id": "[removed]",
            "name": "[removed]"
         },
         "year": {
            "id": "[removed]",
            "name": "[removed]"
         },
         "type": "College"
      }
   ],

我如何使用 PHP 来选择类型为“college”的那个?这是我用来阅读它的内容:

 $token_url = "https://graph.facebook.com/oauth/access_token?"
   . "client_id=[removed]&redirect_uri=[removed]&client_secret=[removed]&code=".$_GET['code']."";


 $response = file_get_contents($token_url);


 parse_str($response);

 $graph_url = "https://graph.facebook.com/me?access_token=" 
   . $access_token;


     $user = json_decode(file_get_contents($graph_url));

所以名称将是 $user->name。

我试过 $user->education->school 但没用。

任何帮助将不胜感激。

谢谢!

【问题讨论】:

  • Facebook 开发者论坛有一些人强烈建议您使用 cURL 而不是 file_get_contents(),因为有些人抱怨它会混淆几个字符。在这种情况下,它非常简单,但您可能不想在获取 access_token 或类似的情况下使用它。

标签: php arrays facebook-graph-api


【解决方案1】:

您的 JSON 文档中的教育是一个数组(注意它的项目被 [ ] 包围),所以您要做的是:

// To get the college info in $college
$college = null;
foreach($user->education as $education) {
    if($education->type == "College") {
        $college = $education;
        break;
    }
}

if(empty($college)) {
    echo "College information was not found!";
} else {
    var_dump($college);
}

结果会是这样的:

object(stdClass)[5]
  public 'school' => 
    object(stdClass)[6]
      public 'id' => string '[removed]' (length=9)
      public 'name' => string '[removed]' (length=9)
  public 'year' => 
    object(stdClass)[7]
      public 'id' => string '[removed]' (length=9)
      public 'name' => string '[removed]' (length=9)
  public 'type' => string 'College' (length=7)

一个更简单的技巧是使用 json_decode 并将第二个参数设置为 true,这会强制结果为数组而不是 stdClass。

$user = json_decode(file_get_contents($graph_url), true);

如果使用数组,则必须将大学检索 foreach 更改为:

foreach($user["education"] as $education) {
    if($education["type"] == "College") {
        $college = $education;
        break;
    }
} 

结果将是:

array
  'school' => 
    array
      'id' => string '[removed]' (length=9)
      'name' => string '[removed]' (length=9)
  'year' => 
    array
      'id' => string '[removed]' (length=9)
      'name' => string '[removed]' (length=9)
  'type' => string 'College' (length=7)

虽然两者都是有效的,但我认为你应该使用数组,它们更容易和更灵活地完成你想做的事情。

【讨论】:

    猜你喜欢
    • 2017-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-01
    相关资源
    最近更新 更多