2011-05-30 47 views
6

我試圖使用stdclass從Facebook的圖形API獲取教育信息。這裏是陣列:在PHP中使用Facebook Graph 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但是沒有奏效。

任何幫助,將不勝感激。

謝謝!

+0

'var_dump($ user)' – zerkms 2011-05-30 01:31:58

+0

Facebook開發者論壇有一些人強烈建議你使用cURL而不是'file_get_contents()',因爲有些人抱怨說它亂碼了幾個字符。 在這種情況下,它非常簡單,但您可能不想在獲取'access_token'等情況下使用它。 – Angad 2011-07-03 15:27:27

回答

6

教育你的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) 

雖然兩者都是有效的,在我意見你應該與陣列,他們更容易,更靈活,你想做什麼。

+0

完美!非常感謝。 – 2011-05-30 03:06:43

相關問題