Reading data from Facebook graphObject

2019-04-20 12:39发布

问题:

A user has accepted my Facebook app. I can now access some of their data. It is returned as a graphObject, which contains something like:

Facebook\GraphObject Object ( [backingData:protected] => Array ( [id] => 11111 [first_name] => Bob [gender] => male [last_name] => Builder [link] => https://www.facebook.com/app_scoped_user_id/11111/ [locale] => de_DE [name] => Bob Builder [timezone] => 2 [updated_time] => 2014-02-14T14:35:54+0000 [verified] => 1 ) )

Unfortunately I cannot get at the data inside this object. Reading it like an array throws an error:

$fbid = $graphObject['id']; // Cannot use object of type Facebook\GraphObject as array
$fbid = $graphObject->id; //  Undefined property: Facebook\GraphObject::$id

How can I get at the ID?

回答1:

If you have casted the response as a GraphObject by using one of the following two methods:

// Get the response typed as a GraphLocation
$loc = $response->getGraphObject(GraphLocation::className());

// or convert the base object previously accessed
// $loc = $object->cast(GraphLocation::className());

You can use the Get properties of the graph object, depending on what kind of object you've casted it as... here's an example for the GraphUser Object:

echo $user->getName();

Or, if you know the name of the property (as shown in the base data), you can use getProperty():

echo $object->getProperty('name');

So in your example, you can use the following to get the id property:

echo $user->getProperty('id');

More examples and documentation here



回答2:

In the New version of Graph API getProperty does not work. For the New version Graph API v2.5 of Facebook Read read data as below :

$fb = new \Facebook\Facebook([
        'app_id' => 'APPIDHERE',
        'app_secret' => 'SECRET HERE',
        'default_graph_version' => 'v2.5',
    ]);
 $asscee_t ="ACCESS TOKEN HERE";
    $response = $fb->get('/me/friends', $asscee_t);
        $get_data = $response->getDecodedBody(); // for Array resonse
        //$get_data = $response->getDecodedBody(); // For Json format result only
        echo $get_data['summary']['total_count']; die; // Get total number of Friends


回答3:

Note that from API version >= 5.0.0 getProperty() has been renamed to getField(). It will be removed from >= v6. So

Instead of

$user->getProperty('name')

Use

$user->getField('name')