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;
Related
I am getting below json data thru Shiprocket API. Now I want to extract value of below variables in PHP code from this json.
I have tried to use json_decode but it did not work and show null value:
$data = json_decode($json);
$sr_status = $data['shipment_status'];
Please suggest the code to retrieve below variables value.
shipment_status , awb_code , courier_company_id
Array
(
[0] => stdClass Object
(
[tracking_data] => stdClass Object
(
[track_status] => 1
[shipment_status] => 7
[shipment_track] => Array
(
[0] => stdClass Object
(
[id] => 180339484
[awb_code] => 11150911492
[courier_company_id] => 55
[shipment_id] => 1711169662
[order_id] => 233223781187
[pickup_date] => 2023-01-11 03:02:00
[delivered_date] => 2023-01-16 12:22:00
[weight] => 0.25
[packages] => 1
[current_status] => Delivered
[delivered_to] => Solapur
[destination] => Solapur
[consignee_name] => ABC
[origin] => Ludhiana
[courier_agent_details] =>
[edd] =>
)
)
[shipment_track_activities] => Array
(
[0] => stdClass Object
(
[date] => 2023-01-16 12:22:00
[status] => 000-T-DL
[activity] => SHIPMENT DELIVERED
[location] => SOLAPUR
[sr-status] => 7
[sr-status-label] => DELIVERED
)
[1] => stdClass Object
(
[date] => 2023-01-16 11:34:00
[status] => 002-S-UD
[activity] => SHIPMENT OUTSCAN
[location] => SOLAPUR
[sr-status] => 17
[sr-status-label] => OUT FOR DELIVERY
)
)
[track_url] => https://shiprocket.co//tracking/11150911492
[etd] => 2023-01-14 17:02:00
[qc_response] => stdClass Object
(
[qc_image] =>
[qc_failed_reason] =>
)
)
)
)
you can try this:
$array = ...; // Your array here
$data= json_decode($array);
$shipment_status = $data[0]->tracking_data->shipment_status;
$awb_code = $data[0]->tracking_data->shipment_track[0]->awb_code;
$courier_company_id = $data[0]->tracking_data->shipment_track[0]->courier_company_id;
Or use $data = json_decode($json,true); which return an array where you can use
foreach($data as $val) {
$shipment_status = $val['tracking_data']['shipment_status'];
foreach ($val['shipment_track'] as $value) {
$awb_code = $value['awb_code'];
$courier_company_id = $value['courier_company_id'];
}
}
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
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] => )
hi i am using facebook graph api PHP SDK . here i am trying to get the logged in user's facebook details , currently i am getting only the basic details which are not required any permissions .
Array
(
[id] => xxxxxxxxx
[name] => Kanishka Bandara Panamaldeniya
[first_name] => Kanishka
[middle_name] => Bandara
[last_name] => Panamaldeniya
[link] => http://www.facebook.com/kanishka.panamaldeniya
[username] => kanishka.panamaldeniya
[hometown] => Array
(
[id] => 108014839219027
[name] => Kandy
)
[location] => Array
(
[id] => 108602292505393
[name] => Colombo, Sri Lanka
)
[quotes] => every action has a reaction....
[work] => Array
(
[0] => Array
(
[employer] => Array
(
[id] => 234117399957729
[name] => Cyber LMJ
)
[location] => Array
(
[id] => 108602292505393
[name] => Colombo, Sri Lanka
)
[position] => Array
(
[id] => 109542932398298
[name] => Software Engineer
)
[start_date] => 2011-08
)
[1] => Array
(
[employer] => Array
(
[id] => 235852306375
[name] => eMarketingEye
)
[position] => Array
(
[id] => 109542932398298
[name] => Software Engineer
)
[start_date] => 2010-09
[end_date] => 2011-08
)
)
[sports] => Array
(
[0] => Array
(
[id] => 103992339636529
[name] => Cricket
)
)
[favorite_teams] => Array
(
[0] => Array
(
[id] => 191485640872790
[name] => Sri Lanka Cricket Team
)
)
[favorite_athletes] => Array
(
[0] => Array
(
[id] => 185101794860886
[name] => Kumara Sangakkara
)
[1] => Array
(
[id] => 119473804782315
[name] => Angelo Mathews
)
[2] => Array
(
[id] => 164574093575397
[name] => Kumar Sangakkara
)
[3] => Array
(
[id] => 169411436417102
[name] => Virat Kohli
)
[4] => Array
(
[id] => 166273026737204
[name] => Lahiru Thirimanne
)
[5] => Array
(
[id] => 101237886616765
[name] => Dinesh Chandimal
)
)
[education] => Array
(
[0] => Array
(
[school] => Array
(
[id] => 34663330581
[name] => Dharmaraja College-Kandy
)
[year] => Array
(
[id] => 138383069535219
[name] => 2005
)
[type] => High School
)
[1] => Array
(
[school] => Array
(
[id] => 112872282058324
[name] => University of Colombo School of Computing
)
[year] => Array
(
[id] => 140617569303679
[name] => 2007
)
[type] => College
)
[2] => Array
(
[school] => Array
(
[id] => 107577089271805
[name] => University of Colombo
)
[type] => Graduate School
[with] => Array
(
[0] => Array
(
[id] => 705760115
[name] => Lasitha Benaragama
)
)
)
)
[gender] => male
[timezone] => 5.5
[locale] => en_US
[languages] => Array
(
[0] => Array
(
[id] => 104023029632921
[name] => Sinhala
)
[1] => Array
(
[id] => 106059522759137
[name] => English
)
)
[verified] => 1
[updated_time] => 2012-07-29T16:34:22+0000
)
now i want to get fields
*email
*birth day
and some other permission requesting fields .
so i am doing
$this->co_config_items = $this->ci->config->item('connections_config');
$fbconfig = array(
'appId' => $this->co_config_items['fb_appid'],
'secret' => $this->co_config_items['fb_secret'],
'cookie' => true,
'domain' => $this->ci->config->item('domain')
);
$this->ci->load->library('3rd/connectors/facebook', $fbconfig);
$facebook = new Facebook($fbconfig);
Facebook::$CURL_OPTS[CURLOPT_SSL_VERIFYPEER] = false;
Facebook::$CURL_OPTS[CURLOPT_SSL_VERIFYHOST] = 2;
$session = $facebook->getSession();
$url = $facebook->getLoginUrl(array(
'canvas' => 1,
'fbconnect' => 0,
'scope' => 'read_stream,friends_likes,user_birthday'
));
if(!$session){
$url = $facebook->getLoginUrl(array(
'canvas' => 1,
'fbconnect' => 0,
'scope' => 'read_stream,friends_likes,user_birthday'
));
echo "<script type='text/javascript'>window.location = '$url';</script>";
}
else{
//echo "<script type='text/javascript'>window.opener.location.href='" . base_url() . "home/auth/get_user_facebook_details_list" . "'; self.close();
//</script>";
try {
$me = $facebook->api('/me');
$this->ci->session->set_flashdata ( 'user_details',$me);
$url=base_url()."home/auth/user_contact_information";
echo "<script type='text/javascript'>window.opener.location.href = '$url';self.close();</script>";
} catch (FacebookApiException $e) {
$this->ci->message->set_error(array('An errror occured , please try again'));
}
}
i am trying to ask permissions by
$url = $facebook->getLoginUrl(array(
'canvas' => 1,
'fbconnect' => 0,
'scope' => 'read_stream,friends_likes,user_birthday'
)):
but it is not asking for any permission , the default array is always printing . why is that . please help . thanks in advance
Try doing this instead:
$url = $facebook->getLoginUrl(array('scope' => 'read_stream,friends_likes,user_birthday'));
i was using the version 2 of PHP sdk , now i am using version 3 , now it is working , thank you very much . i saw some changes in two versions in this function
version 2
public function getLoginUrl($params=array()) {
$currentUrl = $this->getCurrentUrl();
return $this->getUrl(
'www',
'login.php',
array_merge(array(
'api_key' => $this->getAppId(),
'cancel_url' => $currentUrl,
'display' => 'page',
'fbconnect' => 1,
'next' => $currentUrl,
'return_session' => 1,
'session_version' => 3,
'v' => '1.0',
), $params)
);
}
version 3
public function getLoginUrl($params=array()) {
$this->establishCSRFTokenState();
$currentUrl = $this->getCurrentUrl();
// if 'scope' is passed as an array, convert to comma separated list
$scopeParams = isset($params['scope']) ? $params['scope'] : null;
if ($scopeParams && is_array($scopeParams)) {
$params['scope'] = implode(',', $scopeParams);
}
return $this->getUrl(
'www',
'dialog/oauth',
array_merge(array(
'client_id' => $this->getAppId(),
'redirect_uri' => $currentUrl, // possibly overwritten
'state' => $this->state),
$params));
}
in version 3 this i can see this additional code
// if 'scope' is passed as an array, convert to comma separated list
$scopeParams = isset($params['scope']) ? $params['scope'] : null;
if ($scopeParams && is_array($scopeParams)) {
$params['scope'] = implode(',', $scopeParams);
}
in version 2 , there is nothing called scope .and also
in version 2
return $this->getUrl(
'www',
'login.php',
in version 3
return $this->getUrl(
'www',
'dialog/oauth',
I am trying to get the total for the Array in the Object.
I am using print_r to get the following to see whats in it.
stdClass Object ( [data] => Array ( [0] => stdClass Object ( [name] => The Drift Bible [category] => Movie [id] => 227431881228 [created_time] => 2011-02-27T21:41:04+0000 ) [1] => stdClass Object ( [name] => Shooter [category] => Movie [id] => 109671005718938 [created_time] => 2011-02-16T09:18:29+0000 ) [2] => stdClass Object ( [name] => Tron [category] => Movie [id] => 99792857339 [created_time] => 2010-11-29T03:18:06+0000 ))
here is my code to get the information
$movies = json_decode(file_get_contents('https://graph.facebook.com/me/movies?'
.'format=json&access_token=' . $session['access_token']));
Again I just need to get the Array value. Such as 3 in the about example above.
I am very new to this. Any advice will help.
Thanks
Try:
$c = count($movies->data)
//creating facebook_id from facebook_url
$sRequestUrl = 'http://graph'.strstr($a_data['contact_data']['facebook'], '.facebook');
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $sRequestUrl
));
$res = curl_exec($curl);
curl_close($curl);
$res = json_decode($res);
id = $res->id;
about = $res->about;
just call the name of the variable key