Retrieving data from a Facebook GraphObject - php

I have looked around and tried several things, converting it to array and trying to access the object directly.
I want to take out the page ID, name and access token.
Here is my code to get the object with the pages I look after:
$request = new FacebookRequest($session, 'GET', '/'.$userID .'/accounts');
$response = $request->execute();
$graphObject = $response->getGraphObject();
I get the following array using $array = (array) $graphObject;:
Array([*backingData] => Array(
[data] => Array(
[0] => stdClass Object(
[access_token] => CAAVOhgjThxcBAOZB61QxkxI1qdhZCngNZADQloUasFpTRCoZC7hYiDydjXQ9U0vQIjUMyZAeb6aGLKi7VE1btwk8eOPnsEzxyZPhJV1GVoujWlbb6PHo44yIi3D5VPSBRJJuNUOXobSgQNAevpSDZBgZDZD
[category] => Organization
[category_list] => Array(
[0] => stdClass Object(
[id] => 19850828628
[name] => Organization
)
)
[name] => Side Pot Cavan
[id] => 67433931
[perms] => Array(
[0] => ADMINISTER
[1] => EDIT_PROFILE
[2] => CREATE_CONTENT
[3] => MODERATE_CONTENT
[4] => CREATE_ADS
[5] => BASIC_ADMIN
)
)
[1] => stdClass Object(
[access_token] => CAAVOhgjThxcBAD7t6VU3HJAz9AovBJ7OiNzeFRBEQcHDEyHzRmi8oZBMnUyBQHxqNPeTXZBzWaOhCs2ivNWVvHwi5MGJpAuzgsP3d3cVq4LYZBsxcQQbmB5ufZAct250ZBhfENZCFCZAqAPaWvhGFpI5FzM38PwEIZCIZAtdtcvQZC0gZDZD
[category] => Cause
[name] => James Morgan
[id] => 2773587
[perms] => Array(
[0] => ADMINISTER
[1] => EDIT_PROFILE
[2] => CREATE_CONTENT
[3] => MODERATE_CONTENT
[4] => CREATE_ADS
[5] => BASIC_ADMIN
)
)
[2] => stdClass Object(
[access_token] => CAAVOhgjThxcBAIdnByW9TV7ZAxOnBS42nZAWDFEHeb3hPe5lTEMVwzBuZBMiPB99qOM1ks8VafDxLIZBbZCHe8tkDrtjRcPw8DUtpvnBUsNWvqKxt4y7oub10SgHqxRS194At5HBTLJ0K4vpo7qWaXZCIJwZDZD
[category] => Sports venue
[name] => Galway Poker Festival
[id] => 9751854
[perms] => Array(
[0] => ADMINISTER
[1] => EDIT_PROFILE
[2] => CREATE_CONTENT
[3] => MODERATE_CONTENT
[4] => CREATE_ADS
[5] => BASIC_ADMIN
)
)
I have edited the IDs and tokens here for public use.
I am sure I am just missing a next trick to get these values.

You can use the methods getProperty() and getPropertyAsArray() to get the values of a GraphObject. If you want to know what properties there are, use getPropertyNames().
Since this is an array of data (multiple pages the user is admin of), it might be easier to use it as a simple array, like you are trying to - there is a method called asArray() which does exactly this:
$graphObject = $response->getGraphObject();
$data = $graphObject->asArray();
Here's the reference for the Facebook GraphObject class: https://developers.facebook.com/docs/php/GraphObject/4.0.0

so i got a clue from the above answer and moved on:
my finished code was:
foreach ($data as $key => $value) {
if (is_array($value)) {
foreach ($value as $invalue) {
$array = (array) $invalue;
foreach ($array as $key2 => $value2) {
if ($key2=='access_token') {
$c++;
$ats[$c]=$value2;
}
if ($key2=='name') {
$pagenames[$c]=$value2;
}
if ($key2=='id') {
$ids[$c]=$value2;
}
}
}
}
}
So i got a nice clean array from $data = $graphObject->asArray();
then proceeded.
There was another object inside the array so i typecast that to array then run foreach loops over it to get the keys i wanted.
Not the prettiest but it did the job.
thanks

Related

Reading results from PHP Facebook Graph api SDK

I am trying to get a list of all the names & id of people actually going to an event I create. Getting the list using the php graph api for facebook was the easy part and seems to work.
Code (php) the get the data:
//GET ATTENDING
$getattending = "/" . $event_id . "/attending?fields=name,id";
$req_events = new FacebookRequest($session, 'GET', $getattending);
$req_response = $req_events->execute();
$data_array = $req_response->getGraphObject()->asArray();
$counter = array_map("count", $data_array);
$count = $counter['data'];
echo "Attending: $count<BR>";
echo "<PRE>";
print_r($data_array);
echo "</PRE>";
The result:
Array (
[data] => Array
(
[0] => stdClass Object
(
[name] => Thierry Martens
[id] => 788923242
)
[1] => stdClass Object
(
[name] => Lisa Mario Laurier
[id] => 708876902536391
)
[2] => stdClass Object
(
[name] => Ramy Mahfoudhi
[id] => 735036479911364
)
[3] => stdClass Object
(
[name] => Jeremy Verriest Duroisin
[id] => 783108468420824
)
[4] => stdClass Object
(
[name] => Jonas En Svetlana Laurier
[id] => 773139856081632
)
[5] => stdClass Object
(
[name] => Maxime Demerliere
[id] => 849400761761008
)
[6] => stdClass Object
(
[name] => Jeremy Beauchamp
[id] => 10204174155667109
)
[7] => stdClass Object
(
[name] => Sari Jens Delcourte Delusinne
[id] => 10204086515874904
)
[8] => stdClass Object
(
[name] => Pieter Marysse
[id] => 10204911283045115
)
[9] => stdClass Object
(
[name] => Patrick Vanden Bosschelle
[id] => 10202907209181148
)
)
BUT i am having problems to actually gather the data itsels; i simply need the name and the id in simple array or list so i can use it in the rest of the script. Any ideas Anyone?
My second question is the php graph api seems to have a "/eventnr/attending" thing for graph 2.1; showing nr attendants to your event in question; but when i actually call it i get an error stating i need to use graph 2.1 while i uploaded the latest php sdk and can't seem to find a way to change that version. This question is not as important as the one above; but if it works i would need less code :)
Hope you guys can help me :)
!!!! GOT IT !!!!
Did look some further on here and the solutions seems to be pretty easy:
for ($x = 0; $x <= $count; $x++)
{
$names[$x] = $data_array['data'][$x]->name;
$ids[$x] = $data_array['data'][$x]->id;
}
Displays:
$names array:
Array ( [0] => Thierry Martens [1] => Lisa Mario Laurier [2] => Ramy
Mahfoudhi [3] => Jeremy Verriest Duroisin [4] => Jonas En Svetlana
Laurier [5] => Maxime Demerliere [6] => Jeremy Beauchamp [7] => Sari
Jens Delcourte Delusinne [8] => Pieter Marysse [9] => Patrick Vanden
Bosschelle [10] => )
$ids array:
Array ( [0] => 788923242 [1] => 708876902536391 [2] => 735036479911364
[3] => 783108468420824 [4] => 773139856081632 [5] => 849400761761008
[6] => 10204174155667109 [7] => 10204086515874904 [8] =>
10204911283045115 [9] => 10202907209181148 [10] => )
It's like:
$dataArray = $data_array['data'];
$firstPerson = new $dataArray[0];
echo $firstPerson->name;
echo $firstPerson->id;
Maybe you need this, though:
foreach($data_array['data'] as $a){
$o = new $a; $names[] = $o->name; $ids[] = $o->id;
}
// $names is Array of names
// $ids in Array of ids
I added your code but result is the following (empty arrays)
added code:
foreach($data_array['data'] as $a)
{
$o = new $a; $names[] = $o->name; $ids[] = $o->id;
}
echo "FIRST ELEMENT - \$data_array['data'][0]: <BR>";
print_r($data_array['data'][0]); echo "<BR><BR>";
echo "\$names array: <BR>";
print_r($names); echo "<BR><BR>";
echo "\$ids array: <BR>";
print_r($ids); echo "<BR><BR>";
Result of the echo & print_r:
FIRST ELEMENT - $data_array['data'][0]:
stdClass Object ( [name] => Thierry Martens [id] => 788923242 )
$names array:
Array ( [0] => [1] => [2] => [3] => [4] => [5] => [6] => [7] => [8] => [9] => )
$ids array:
Array ( [0] => [1] => [2] => [3] => [4] => [5] => [6] => [7] => [8] => [9] => )

decode json response to get json parameter value

Here is my json response:
stdClass Object ( [is_claimed] => [rating] => 4 [mobile_url] => http://m.yelp.com/biz/the-waterboy-sacramento [rating_img_url] => http://s3-media4.ak.yelpcdn.com/assets/2/www/img/c2f3dd9799a5/ico/stars/v1/stars_4.png [review_count] => 455 [name] => The Waterboy [snippet_image_url] => http://s3-media1.ak.yelpcdn.com/photo/SZyFYvQmHWSLhK96SSzwwA/ms.jpg [rating_img_url_small] => http://s3-media4.ak.yelpcdn.com/assets/2/www/img/f62a5be2f902/ico/stars/v1/stars_small_4.png [url] => http://www.yelp.com/biz/the-waterboy-sacramento [menu_date_updated] => 1387494198 [reviews] => Array ( [0] => stdClass Object ( [rating] => 5 [excerpt] => AMAZING again, went here last Thursday at 5:00pm. Greeted by friendly man, he asked if we had a reservation, I said, 'no, do we need one?' He said, I'm... [time_created] => 1395158338 [rating_image_url] => http://s3-media1.ak.yelpcdn.com/assets/2/www/img/f1def11e4e79/ico/stars/v1/stars_5.png [rating_image_small_url] => http://s3-media1.ak.yelpcdn.com/assets/2/www/img/c7623205d5cd/ico/stars/v1/stars_small_5.png [user] => stdClass Object ( [image_url] => http://s3-media1.ak.yelpcdn.com/photo/SZyFYvQmHWSLhK96SSzwwA/ms.jpg [id] => H0qUqWctz5Ms6qdeaIvjFw [name] => Lori T. ) [rating_image_large_url] => http://s3-media3.ak.yelpcdn.com/assets/2/www/img/22affc4e6c38/ico/stars/v1/stars_large_5.png [id] => bZznirkpADmW3Qcpc5u_VA ) ) [phone] => 9164989891 [snippet_text] => AMAZING again, went here last Thursday at 5:00pm. Greeted by friendly man, he asked if we had a reservation, I said, 'no, do we need one?' He said, I'm... [image_url] => http://s3-media1.ak.yelpcdn.com/bphoto/9e5sodvvP3p6_53wOqVTcg/ms.jpg [categories] => Array ( [0] => Array ( [0] => French [1] => french ) [1] => Array ( [0] => Italian [1] => italian ) ) [display_phone] => +1-916-498-9891 [rating_img_url_large] => http://s3-media2.ak.yelpcdn.com/assets/2/www/img/ccf2b76faa2c/ico/stars/v1/stars_large_4.png [menu_provider] => single_platform [id] => the-waterboy-sacramento [is_closed] => [location] => stdClass Object ( [city] => Sacramento [display_address] => Array ( [0] => 2000 Capitol Ave [1] => Midtown [2] => Sacramento, CA 95811 ) [neighborhoods] => Array ( [0] => Midtown ) [postal_code] => 95811 [country_code] => US [address] => Array ( [0] => 2000 Capitol Ave ) [state_code] => CA ) )
which I get using:
$response = json_decode($data);
print_r($response);
echo $response["rating"]; //Why this does not give json response value?
Pass true into the second parameter of json_decode to return an array (which is how you're trying to access it):
$response = json_decode($data, true); // associative array returned
print_r($response);
echo $response["rating"]; // 4
Manual
Otherwise, access the rating as a property of the object that you've got:
$response = json_decode($data);
echo $response->rating; // 4

Convert Facebook decoded json to PHP array

I have the following PHP code:
define('TOKEN_FILE', 'fb_page_accestoken.txt'); // dont need to change this
$fb = new Facebook(array(
'appId' => FB_APP_ID,
'secret' => FB_APP_SECRET,
'cookie' => true,
));
$access_token = file_get_contents('fb_app_token.txt');
$response = "https://graph.facebook.com/me/accounts?access_token=".$access_token;
$responsez = json_decode(file_get_contents($response ,true));
print_r($responsez);
When I use the above code I decode the JSON string and get the following:
stdClass Object ( [data] => Array ( [0] => stdClass Object ( [category] => Media/news/publishing [name] => PAGE ABC [access_token] => abcdefghijklmnopqrstuvwxyz1234567890 [perms] => Array ( [0] => ADMINISTER [1] => EDIT_PROFILE [2] => CREATE_CONTENT [3] => MODERATE_CONTENT [4] => CREATE_ADS [5] => BASIC_ADMIN ) [id] => 35645645678735 ) [1] => stdClass Object ( [category] => Entertainment website [name] => Page 123 [access_token] => abcdefghijklmnopqrstuvwxyz1234567890 [perms] => Array ( [0] => ADMINISTER [1] => EDIT_PROFILE [2] => CREATE_CONTENT [3] => MODERATE_CONTENT [4] => CREATE_ADS [5] => BASIC_ADMIN ) [id] => 1364564569777454 )
How can I get the above into a PHP array? For example to be able to extract the access_token of page id 1364564569777454.
responsez = json_decode(file_get_contents($response), true);
The second param in json_decode allow convert returned object into associative arrays.
$arr = array();
foreach($responsez->data as $obj){
$arr[] = array("page_id"=>$obj->id,"access _token"=>$obj->access_token);
}
print_r($arr);
I was having troubles with the accounts JSON and this worked better for me:
$request = (new FacebookRequest($session, 'GET', '/' . $this->userID . '/accounts'))->execute();
$graphObject = json_decode($request->getRawResponse(), true);
foreach ($graphObject['data'] as $page) { // array['data', 'paging']
if ($page['id'] == $this->fbAppPageID) {
$this->pageToken = $page['access_token'];
}
}
return $this->pageToken;

Get value in mutli array

How would i get the value of a key in an array?
The array is done by google shopping api which is:
// Valid source values are "public", "cx:cse", and "gan:pid"
// See http://code.google.com/apis/shopping/search/v1/getting_started.html#products-feed
$source = "public";
// For more information about full text search with the shopping API, please
// see http://code.google.com/apis/shopping/search/v1/getting_started.html#text-search
$query = "\"mp3 player\" | ipod";
//The order in which the API returns products is defined by a ranking criterion.
// See http://code.google.com/apis/shopping/search/v1/getting_started.html#ranking
$ranking = "relevancy";
$results = $service->products->listProducts($source, array(
"country" => "UK",
"q" => $query,
"rankBy" => $ranking,
));
print "<h1>Shopping Results</h1><pre>" . print_r($results, true) . "</pre>";
I have the following array which outputs:
Shopping Results
Array
(
[kind] => shopping#products
[etag] => "*********"
[id] => tag:google.com,2010:shopping/products
[selfLink] => https://www.googleapis.com/shopping/search/v1/public/products?country=UK&q=iphone&rankBy=relevancy
[nextLink] => https://www.googleapis.com/shopping/search/v1/public/products?country=UK&q=iphone&rankBy=relevancy&startIndex=26
[totalItems] => 771622
[startIndex] => 1
[itemsPerPage] => 25
[currentItemCount] => 25
[requestId] => 0CMjH976CqbECFYNWtAodLRwAAA
[items] => Array
(
[0] => Array
(
[kind] => shopping#product
[id] => tag:google.com,2010:shopping/products/5735617/11254757413841304510
[selfLink] => https://www.googleapis.com/shopping/search/v1/public/products/5735617/gid/11254757413841304510
[product] => Array
(
[googleId] => 11254757413841304510
[author] => Array
(
[name] => Amazon.co.uk
[accountId] => 5735617
)
[creationTime] => 2012-05-04T05:03:50.000Z
[modificationTime] => 2012-07-20T02:02:16.000Z
[country] => GB
[language] => en
[title] => Apple iPod touch 8GB - Black - 4th Generation (Latest Model - Launched Sept 2010)
[description] => Apple iPod touch 8GB - Black - 4th Generation (Latest Model - Launched Sept 2010)
[link] => http://www.amazon.co.uk/dp/B0040GIZTI/ref=asc_df_B0040GIZTI8843997?smid=A1YZ4RXO7GUOYN&tag=googlecouk06-21&linkCode=asn&creative=22218&creativeASIN=B0040GIZTI
[brand] => Apple
[condition] => new
[gtin] => 00885909394739
[gtins] => Array
(
[0] => 00885909394739
)
[mpns] => Array
(
[0] => MC540BT/A
)
[inventories] => Array
(
[0] => Array
(
[channel] => online
[availability] => inStock
[price] => 135.95
[shipping] => 1.99
[currency] => GBP
)
)
[images] => Array
(
[0] => Array
(
[link] => http://ecx.images-amazon.com/images/I/41p2rNmazRL.jpg
[status] => available
)
)
)
)
[1] => Array
(
[kind] => shopping#product
[id] => tag:google.com,2010:shopping/products/5735617/4597224105326146239
[selfLink] => https://www.googleapis.com/shopping/search/v1/public/products/5735617/gid/4597224105326146239
[product] => Array
(
[googleId] => 4597224105326146239
[author] => Array
(
[name] => Amazon.co.uk
[accountId] => 5735617
)
[creationTime] => 2012-05-04T05:03:50.000Z
[modificationTime] => 2012-07-20T02:02:16.000Z
[country] => GB
[language] => en
[title] => SanDisk Sansa Clip+ 8GB MP3 Player with Radio and Expandable MicroSD/SDHC Slot - Black
[description] => 8 GB memory Digital FM-tuner with 40 preset radio stations Extendable microSD/microSDHC card slot
[link] => http://www.amazon.co.uk/dp/B002NX0ME6/ref=asc_df_B002NX0ME68843997?smid=A3P5ROKL5A1OLE&tag=googlecouk06-21&linkCode=asn&creative=22206&creativeASIN=B002NX0ME6
[brand] => SanDisk
[condition] => new
[gtin] => 00619659059989
[gtins] => Array
(
[0] => 00619659059989
)
[mpns] => Array
(
[0] => SDMX18-008G-E46K
)
[inventories] => Array
(
[0] => Array
(
[channel] => online
[availability] => inStock
[price] => 46.95
[shipping] => 0
[currency] => GBP
)
)
[images] => Array
(
[0] => Array
(
[link] => http://ecx.images-amazon.com/images/I/419U6bYDF1L.jpg
[status] => available
)
)
)
)
I don't need all this data i just need 3-4 of the keys but how would i access them? How would i echo the value of say [title] from each array?
This should work:
foreach( $results as $result)
foreach( $result['product'] as $product)
echo $product['title'];
You could either loop through the array like pointed out above or possibly use array_walk_recursive like this:
$title_array = array();
array_walk_recursive($input_array, 'find_titles');
function find_titles($value, $key) {
global $title_array;
if ($key == 'title') {
$title_array[] = $value;
}
}
This might be a better solution if you you are not certain what the structure of the input array will be (i.e. how many levels deep the key you are looking for is nested).
To output the title of each product in $results:
foreach ($results as $result) {
echo $result['product']['title'];
}
Consider using array_walk_recursive
Working example
<?php
$a = array("hai", array("ha"=>1, "hai"=>2, array("a"=>1, "b"=>2)));
function test($item, $key)
{
echo "$key holds $item\n";
}
array_walk_recursive($a, 'test');
0 holds hai
ha holds 1
hai holds 2
a holds 1
b holds 2
If you are interested only in title
Consider using foreach
foreach($results['item'] as $result) {
echo $result['product']['title'];
}

parse PHP array

I have managed to get to the stage where I have an array that looks like this. Used (zend_json to decode a json response)
Array
(
[response] => Array
(
[status] => ok
[userTier] => free
[total] => 10
[startIndex] => 1
[pageSize] => 10
[currentPage] => 1
[pages] => 1
[results] => Array
(
[0] => Array
(
[id] => lifeandstyle/series/cycling
[type] => series
[webTitle] => Cycling
[webUrl] => http://www.guardian.co.uk/lifeandstyle/series/cycling
[apiUrl] => http://content.guardianapis.com/lifeandstyle/series/cycling
[sectionId] => lifeandstyle
[sectionName] => Life and style
)
[1] => Array
(
[id] => sport/cycling
[type] => keyword
[webTitle] => Cycling
[webUrl] => http://www.guardian.co.uk/sport/cycling
[apiUrl] => http://content.guardianapis.com/sport/cycling
[sectionId] => sport
[sectionName] => Sport
)
How would I go about parsing only the elements that are [webTitle] and [webUrl]
Thanks!
You can't specifically parse only those parts, but you can iterate over the results and access them.
foreach ($val['response']['results'] as $result) {
$title = $result['webTitle'];
$url = $result['webUrl'];
// ...
}

Categories