2012-04-25 96 views
0

我想解碼用戶的位置。 假設Facebook解碼Json

"id": "100000564553314", 
"name": "Adi Mathur", 
"location": { 
     "id": "106487939387579", 
     "name": "Gurgaon, Haryana" 
} 

我使用的腳本來獲取名稱,但位置是給我一個錯誤

不能使用類型爲stdClass的對象作爲數組

$token_url = "https://graph.facebook.com/oauth/access_token?" 
    . "client_id=" . $app_id . "&redirect_uri=" . urlencode($my_url) 
    . "&client_secret=" . $app_secret . "&code=" . $code; 

$response = file_get_contents($token_url); 
$params = null; 
parse_str($response, $params); 

$graph_url = "https://graph.facebook.com/me?access_token=" 
. $params['access_token']; 

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

echo $_SESSION['name']=$user->name; // WORKS 
echo $_SESSION['fbid']=$user->id;  // WORKS 

echo $_SESSION['location']=$user->location[0]; // ERROR 
echo $_SESSION['location']=$user->location->name; // ERROR 

回答

1

考慮使用:

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

這將確保$ user是一個關聯數組而不是一個對象。然後你可以設置你的$ _SESSION變量,像這樣:

$_SESSION['name']=$user['name']; 
$_SESSION['fbid']=$user['id']; 
$_SESSION['location']=$user['location']['name']; 
1

添加第二個參數作爲assoctruejson_decode

json_decode(file_get_contents(...),true); 

這將返回一個數組,而不是一個對象。然後你可以使用數組符號[]而不是對象運算符->