coderloop coderloop - 2 months ago 12
reST (reStructuredText) Question

Handling JSON object from Twitter API response

I'd like to retrieve all Twitter IDs of users that follow a certain other user (e.g. @Google) through the Twitter API. While the request works in Postman, I cannot get it working in PHP. It seems that $userids is not a string, so json_decode cannot process it. Code below. Thanks for your help!

<?php
require "twitteroauth/autoload.php";

use Abraham\TwitterOAuth\TwitterOAuth;

ini_set('max_execution_time', 600);
ini_set('memory_limit', '1024M');

$consumerKey = 'redacted';
$consumerKeySecret = 'redacted';
$accessToken = 'redacted';
$accessTokenSecret = 'redacted';
$cursor = -1; // first page

$connection = new TwitterOAuth($consumerKey, $consumerKeySecret, $accessToken, $accessTokenSecret);
$content = $connection->get("account/verify_credentials");

$userids = $connection->get("followers/ids", ["cursor" => -1, "screen_name" => "google", "count" => 5000]);

echo $userids;

$data = json_decode($userids);
foreach ($data as $ids => $value) {
// tbd
}
var_dump($data);

?>

Answer

$userids is an array, as you can see in the TwitterOAuth source:

$response = JsonDecoder::decode($result, $this->decodeJsonAsArray);

That means you don't have to json_decode() it again, as it's already a PHP array.

Comments