I am trying to get the post share count using the PHP Facebook API (php-sdk-v4).
Right now I can get most of the information that I want, but it looks like the share count is in a different format.
Here's a basic example of my code.
$request = $this->fb->get(
"/$id/posts?fields=id,message,shares,likes.limit(1).summary(true),comments.limit(1).summary(true)&limit=10"
);
$posts = $request->getGraphEdge();
For the returned $posts I can loop through and retrieve the info that I want for most of the fields using this code:
$id = $post->getField( 'id' );
$message = $post->getField( 'message' );
Likes and Comments are retrieved a little different, but I was able to get it using this:
$likes = $post->getField( 'likes' )->getTotalCount();
$comments = $post->getField( 'comments' )->getTotalCount();
The problem that I am running into is that the shares count is returned as a "GraphNode" Object and I get an error when I try to use getTotalCount. The object $post->getField( 'shares' ) looks like this:
[shares] => Facebook\GraphNodes\GraphNode Object
(
[items:protected] => Array
(
[count] => 1
)
)
I can not figure out the proper way to retrieve this variable, which in this case would be 1.
Any help would be appreciated. Thank you!
Try this way, I think it's "proper". it's important to check if $graphNode->getField('shares')
is not null before asking for ->getField('count')
.
$request = $fb->get('/' . $id . '/posts?fields=id,message,shares,likes.limit(1).summary(true),comments.limit(1).summary(true)&limit=10');
foreach ($request->getGraphEdge() as $graphNode) {
// Sometimes "getField" function can return a null value
if ($graphNode->getField('shares')) {
$numberShares = $graphNode->getField('shares')->getField('count');
}
}