Skip to content

Instantly share code, notes, and snippets.

@maurerbot
Created January 10, 2012 23:14
Show Gist options
  • Save maurerbot/1591823 to your computer and use it in GitHub Desktop.
Save maurerbot/1591823 to your computer and use it in GitHub Desktop.
PHP Script to get Twitter mutual relationship ids and their user details
//sharing this logic because twitter doesn't give you and end point to get mutual relationships (uses zend mvc framework for requests but it is easy enough to use something else to make the API requests)
//note: $this->source variable is a standard object that holds access token and user information for the user doing the requests
$cursor = -1; //initial position for twitter API friends and follower endpoint (important for users with more then 5000 followers/friends)
do {
//get the first 5000 following ids
$client = new Zend_Http_Client;
$client->setUri('https://api.twitter.com/1/friends/ids.json');
$client->setMethod(Zend_Http_Client::GET);
$client->setParameterGet('cursor', $cursor);
$client->setParameterGet('user_id', $this->source->source_user_id); //id of user querying
//get the first 5000 follower ids
$client2 = new Zend_Http_Client;
$client2->setUri('https://api.twitter.com/1/followers/ids.json');
$client2->setMethod(Zend_Http_Client::GET);
$client2->setParameterGet('cursor', $cursor);
$client2->setParameterGet('user_id', $this->source->source_user_id);
//send following request
$following = $client->request();
$following = Zend_Json::decode($following->getBody(), Zend_Json::TYPE_OBJECT)->ids;
//send follower request
$followers = $client2->request();
$followers = Zend_Json::decode($followers->getBody(), Zend_Json::TYPE_OBJECT)->ids;
//create array of similar ids
$mutual = array_intersect($followers, $following);
$friends = array(); // <-- THIS IS WHERE YOUR FINAL RESULT IS STORED. do what you need with this array after storing details
for($start = 0; $start < count($mutual) - 1; $start += 100) {
//get user details for first 100 (max request amount) and needs authentication
$client = new Zend_Http_Client;
$client->setUri('https://api.twitter.com/1/users/lookup.json');
$client->setMethod(Zend_Http_Client::GET);
$client->setParameterGet('access_token', $this->source->oauth_user_key); //access token for the user doing the query
$client->setParameterGet('user_id', implode(',', array_slice($mutual, $start, 100, true)));
$response = $client->request();
$response = Zend_Json::decode($response->getBody(), Zend_Json::TYPE_OBJECT);
//merge user details results into friends array and then do the next 100
$friends = array_merge($friends, $response);
}
$cursor++; // increment cursor for api call if more then 5000 results
} while ( count($mutual) == 5000 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment