2012-04-25 61 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); 

这将返回一个数组,而不是一个对象。然后你可以使用数组符号[]而不是对象运算符->