I’m trying to get the education info from Facebook’s graph API using stdclass. here’s the array:
"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"
}
],
How can I use PHP to select the one with type “college”? Here’s what I’m using to read it:
$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));
So the name would be $user->name.
I tried $user->education->school but that didn’t work.
Any help would be appreciated.
Thanks!
Education in your JSON document is an array (notice that its items are surrounded by [ ]), so what you have to do is:
The result would be something like:
An easier trick would be to use json_decode with the second param set to true, which forces the results to be arrays and not stdClass.
If you go with arrays, you have to change the college retrieval foreach to:
and the result will be:
Although both are valid, in my opinion you should go with arrays, they are easier and more flexible for what you want to do.