Skip to content

Instantly share code, notes, and snippets.

@craigwillis85
Created January 27, 2016 12:35
Show Gist options
  • Select an option

  • Save craigwillis85/bec0f886bfd15fc3ff20 to your computer and use it in GitHub Desktop.

Select an option

Save craigwillis85/bec0f886bfd15fc3ff20 to your computer and use it in GitHub Desktop.
// since_id comes form database - set at a specific date
$results = SearchTwitter::get_tweets($keyword, $since_id);
// We'll save the tweets in $result back to the database
// since_id will therfore be updated to the newest tweet
class SearchTwitter
{
public static function get_tweets($keyword, $since_id) {
$connection = new Abraham\TwitterOAuth\TwitterOAuth(
KEY,
KEY,
TOKEN,
TOKEN
);
$results = array();
$max_id = 0;
// Set initial search params
$params = array(
"q" => $keyword,
"result_type" => "recent",
"include_entities" => true,
"count" => 100
);
while (true) {
// First API call - get 100 latest tweets
if ($max_id == 0) {
// Set the since_id
$params['since_id'] = $since_id;
$statuses = $connection->get("search/tweets",
$params
);
} else {
// Collect older tweets
// Use max_id now to 'page' through results
$params['max_id'] = $max_id;
unset($params['since_id']);
$statuses = $connection->get("search/tweets",
$params
);
}
// Exit on no results or errors
// The API rate limit is 180 every 15 minutes
if (!$statuses || !isset($statuses->statuses)) {
break;
}
$tweets = $statuses->statuses;
// Exit when no more tweets are returned
if (count($tweets) == 0) {
break;
}
$results = array_merge($results, $tweets);
$max_id = $statuses->search_metadata->max_id;
// Check we have more results
if (!isset($statuses->search_metadata->next_results)) {
break;
}
}
return $results;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment