有没有办法用Facebook PHP SDK V4以Json或数组格式获取Facebook响应?

use*_*543 1 php facebook facebook-graph-api facebook-php-sdk

例如一个请求

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

回报

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 
    ) 
)
Run Code Online (Sandbox Code Playgroud)

那是.我想检索数组中的所有响应,没有这些stdClass对象.就像它在api的上一个版本中一样.谢谢.

Tam*_*ama 8

一种更简单的方法可能是从$ response中获取原始JSON并自行解码:

$request = new FacebookRequest($session, 'GET', '/me/accounts?fields=id,name,access_token');
$response = $request->execute();
$array = json_decode($response->getRawResponse(), true);
print_r($array);
Run Code Online (Sandbox Code Playgroud)

更新

PHP SDK 5.0+开始,您可以getDecodedBody()FacebookResponse对象上使用(这将为您执行JSON解码并返回一个数组).

$fb = new Facebook([...]);
$response = $fb->get('/me', '{access-token}');
$array = $response->getDecodedBody();
Run Code Online (Sandbox Code Playgroud)

  • 我正在使用这种方式,似乎工作得很好.只有更新是getRawResponse()看起来像旧的规范,从5.0开始它现在应该使用$ response-> getBody()https://developers.facebook.com/docs/php/FacebookResponse/5.0.0 (3认同)