PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, March 14, 2022

[FIXED] Is there a way to get facebook response in Json or array format with Facebook PHP SDK V4?

 March 14, 2022     facebook, facebook-graph-api, facebook-php-sdk, php     No comments   

Issue

For example a request like

$request = new FacebookRequest($session, 'GET','/me/accounts?fields=id,name,access_token');
$response = $request->execute();
$arrayResult = $response->getGraphObject()->asArray();
print_r($arrayResult);

returns

Array ( 
    [data] => Array ( 
        [0] => stdClass Object ( 
            [id] => 01010011100001111000111 #it's a fake id 
            [name] => MyAwesomePageName    #And a fake name 
        ) 
    ) 
    [paging] => stdClass Object ( 
        [next] => https://graph.facebook.com/v2.0/01010011100001111000111/accounts?fields=id,name&access_token=RanDoMAndFaaKKeEACCessToKen&limit=5000&offset=5000&__after_id=enc_IdOnOTKnoWWhAtThiSIs 
    ) 
)

Thats is. I would like to retrieve all the response in array and without theses stdClass objects. Just like it was in the previous version of their api. Thanks.


Solution

The Facebook SDK's asArray() method is limited as you've discovered. However, you can manually convert an object to an array using the get_object_vars( $object ); function. In your example, you can do something like:

$array = get_object_vars( $arrayResult['data'][0] );

This will convert the page Object into an array. The function isn't recursive, so you'll need to convert each object to an array.

You can use a recursive function like this:

function object_to_array($obj) {
    $arr = array();
    if($obj instanceOf GraphObject){
        if(is_scalar($obj->asArray()) ) 
            $arr = $obj->asArray();
        else{
            foreach ($obj->getPropertyNames() as $propName) {
                $arr[$propName] = object_to_array($obj->getProperty($propName));
            }
        }
    }else if(is_array($obj)){
        foreach ($obj as $propKey => $propValue) {
            $arr[$propKey] = object_to_array($obj[$propValue]);
        }
    }else $arr = $obj;
    return $arr;
}


Answered By - Niraj Shah
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing