A Simple Way to Search Tweets by a Hashtag with Twitter API v1.1

The followings are sample PHP codes to search tweets by a hashtag, in a simple form with The first PHP Library to support OAuth for Twitter’s REST API which supports the version 1.1 of Twitter API.

Sample Code – Search Tweets by a Hashtag

The following code searches tweets containing #WorldSeries hashtag by a query "q" => "#WorldSeries".

<?php
require_once 'lib/twitteroauth.php';

define('CONSUMER_KEY', 'your_consumer_key');
define('CONSUMER_SECRET', 'your_consumer_secret');
define('ACCESS_TOKEN', 'your_access_token');
define('ACCESS_TOKEN_SECRET', 'your_access_token_secret');

$toa = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET);

$query = array(
  "q" => "#WorldSeries"
);

$results = $toa->get('search/tweets', $query);

foreach ($results->statuses as $result) {
  echo $result->user->screen_name . ": " . $result->text . "\n";
}

Sample Code – Search Popular/Recent Tweets by a Hashtag

You can search popular or recent tweets by adding "result_type" => "popular" or "result_type" => "recent" parameter to a query.

$query = array(
  "q" => "#WorldSeries",
  "result_type" => "popular"
);
$query = array(
  "q" => "#WorldSeries",
  "result_type" => "recent"
);

50 thoughts on “A Simple Way to Search Tweets by a Hashtag with Twitter API v1.1

  1. Kevin

    Hi,

    I would like to know if it is possible to get Tweets from a few days ago, because the hashtag I’m searching for isn’t the most popular. That way I don’t get alot of results, and I would like to gather tweets from more days ago.

    Thanks in advance,
    Kevin

    1. techiella Post author

      Yes, it’s possible. You can use since and until options. The following code searches tweets tagged with “#Niche” since 5/17 until 5/19.

      <?php
      require_once 'lib/twitteroauth.php';
      
      define('CONSUMER_KEY', 'your_consumer_key');
      define('CONSUMER_SECRET', 'your_consumer_secret');
      define('ACCESS_TOKEN', 'your_access_token');
      define('ACCESS_TOKEN_SECRET', 'your_access_token_secret');
      
      $toa = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET);
      
      $max_id = "";
      foreach (range(1, 10) as $i) { // up to 10 result pages
      
        $query = array(
          "q" => "#Niche since:2014-05-17 until:2014-05-19", // Change here
          "count" => 20,
          "result_type" => "recent",
          "max_id" => $max_id,
        );
      
        $results = $toa->get('search/tweets', $query);
      
        foreach ($results->statuses as $result) {
          echo " [" . $result->created_at . "] " . $result->user->screen_name . ": " . $result->text . "\n";
          $max_id = $result->id_str; // Set max_id for the next search result page
        }
      }
      
  2. Corentin

    Hi,

    First, thank you for the tuto !
    Do you know how to get the picture of each user who wrote a tweet ?

    Thanks in advance and sorry for my english.

    Corentin

    1. techiella Post author

      You mean user profile image? Please try the code on #comment-3558. The users/lookup API provides user’s info including a profile image URL. The following code searches tweets by hashtag, and then gets the profile image of each user:

      require_once 'lib/twitteroauth.php';
      
      define('CONSUMER_KEY', 'your_consumer_key');
      define('CONSUMER_SECRET', 'your_consumer_secret');
      define('ACCESS_TOKEN', 'your_access_token');
      define('ACCESS_TOKEN_SECRET', 'your_access_token_secret');
      
      $toa = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET);
      
      $users = array();
      
      $max_id = "";
      foreach (range(1, 1) as $i) { // up to 1 page
        $query = array(
          "q" => "#Niche",
          "count" => 10,
          "result_type" => "recent",
          "max_id" => $max_id,
        );
      
        $results = $toa->get('search/tweets', $query);
      
        foreach ($results->statuses as $result) {
          $users[] =  $result->user->screen_name; // Remember users
          $max_id = $result->id_str; // Set max_id for the next search page
        }
      }
      
      // You can get user info for up to 100 users per request,
      // as specified by comma-separated values.
      $user_objs = $toa->get('users/lookup', array('screen_name' => implode(',', $users)));
      
      foreach ($user_objs as $user_obj) {
        echo "[" . $user_obj->name . "][" . $user_obj->screen_name . "][" . $user_obj->profile_image_url . "]\n";
      }
      

      ou will get a result like the following, that contains profile image URLs for users who have a tweet found by the search.

      [AainaA-Ridtz A R][ARARidtz][http://pbs.twimg.com/profile_images/468112799151828994/eoI7bakK_normal.jpeg]
      [Sem Smo Today][semsmotoday][http://pbs.twimg.com/profile_images/1704607389/logo1_normal.gif]
      [Lauren Dyke][LozzerDee][http://pbs.twimg.com/profile_images/468798054112317441/-YuxmIvA_normal.jpeg]
      [ry m. sal][RySalinetti][http://pbs.twimg.com/profile_images/1148306654/fortwitter_normal.jpg]
      [PeterZilahyIngerman][PZI_org][http://pbs.twimg.com/profile_images/465288955177365504/_lDF8Rnh_normal.jpeg]
      [Jalel MOKNI][jalelmokni][http://pbs.twimg.com/profile_images/459853031597559809/PSwUENEd_normal.jpeg]
      [jenn sarria][jennsarria][http://pbs.twimg.com/profile_images/438035499077222402/kdFn4Yjo_normal.jpeg]
      [James rigney][rigsalot][http://pbs.twimg.com/profile_images/3080986546/be8f419b40cf887c0f7e4816f2608874_normal.jpeg]
      [Training Magazine][TrainingMagUS][http://pbs.twimg.com/profile_images/1738136844/Cropped_for_Twitter_normal.png]
      [Sophie Khan & Co][SophieKhanSols][http://pbs.twimg.com/profile_images/453267792284758016/KirN6MHv_normal.jpeg]
      
      1. Corentin

        Excuse me but i’ve an other question.
        How to put in relation the tweet and the profil pic ?

        Thank you a lot !!

  3. Corentin

    My code :

    “#orange”,
    “count” => 10,
    “result_type” => “recent”,
    “max_id” => $max_id,
    );

    $results = $toa->get(‘search/tweets’, $query);

    foreach ($results->statuses as $result) {
    $users[] = $result->user->screen_name; // Remember users
    $max_id = $result->id_str; // Set max_id for the next search page
    echo $result->text;
    }
    }

    // You can get user info for up to 100 users per request,
    // as specified by comma-separated values.
    $user_objs = $toa->get(‘users/lookup’, array(‘screen_name’ => implode(‘,’, $users)));

    foreach ($user_objs as $user_obj) {
    echo “[” . $user_obj->name . “][” . $user_obj->screen_name . “][” . $user_obj->profile_image_url . “]\n”;
    }

    ?>

    1. techiella Post author

      I simplified the previous code (users/lookup related code was not needed). Please try this one:

      require_once 'lib/twitteroauth.php';
      
      define('CONSUMER_KEY', 'your_consumer_key');
      define('CONSUMER_SECRET', 'your_consumer_secret');
      define('ACCESS_TOKEN', 'your_access_token');
      define('ACCESS_TOKEN_SECRET', 'your_access_token_secret');
      
      $toa = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET);
      
      $max_id = "";
      foreach (range(1, 1) as $i) { // up to 1 page
        $query = array(
          "q" => "#orange",
          "count" => 10,
          "result_type" => "recent",
          "max_id" => $max_id,
        );
      
        $results = $toa->get('search/tweets', $query);
      
        foreach ($results->statuses as $result) {
          echo "[" . $result->user->profile_image_url . "]" .
               "[" . $result->user->name . "]" .
               "[" . $result->user->screen_name . "]" .
               "[" . $result->text . "]\n";
      
          $max_id = $result->id_str; // Set max_id for the next search page
        }
      }
      
  4. name

    How do I get the keys and tokens? Why can’t someone make a complete tutorial that includes EVERYTHING? Fucking Twitter API…

    1. techiella Post author

      Short tutorial:

      1. Visit https://dev.twitter.com/
      2. Sign in with your Twitter account.
      3. Click “My applications” button in the menu at the top right corner.
      4. Click “Create New App” button.
      5. Fill in a form and send it by clicking “Create Your Twitter Application” button.
      6. Click “API Keys” tab.
      7. Click “Create my access token” button at the bottom.

      Then you can get the following 4 things:

      • API Key (Consumer Key)
      • API secret (Consumer secret)
      • Access token
      • Access token secret
  5. jsg

    Hi,

    I am using your code to define the user and then a hashtag within that time and display the latest one.

    However, i cant seem to get it to work – I thought that the variable “from:user” would work but it doesnt.


    function search(array $query)
    {
    $toa = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET);
    return $toa->get('search/tweets', $query);
    }

    $query = array(
    "q" => "#dribbble",
    "count" => 1,
    "result_type" => "recent",
    "lang" => "en",
    );

    $results = search($query);

    foreach ($results->statuses as $result) {

    echo $result->text . ": " . $result->user->screen_name . "\n\n";
    }

    1. techiella Post author

      What output do you expect?
      I did “copy & paste” your code and executed it. I got the following tweet.

      How do I invite a player in #dribbble ? @dribbble #dribbbleinvite: me_Sravan
      
  6. Mike

    This is great, thanks so much.

    I’m using the following code but i’d like it to display one random result every time the page refreshes and not just the latest post – any ideas?

    "tuaj",
    "count" => 1,
    "result_type" => "recent",
    "max_id" => $max_id,
    );

    $results = $toa->get('search/tweets', $query);

    foreach ($results->statuses as $result) {
    echo "[" . $result->user->screen_name . "]" .
    "[" . $result->text . "]\n";

    $max_id = $result->id_str; // Set max_id for the next search page
    }
    }

    1. techiella Post author

      The following code prints a tweet, which is selected randomly from 500 tweets (including both “popular” and “recent”) found by Twitter search with the keyword “tuaj”.

      In the following code, I’m using the array $tweetAry to store tweets. In practice, however, it’s better to store/accumulate tweets into a database, and read them from database every time a page refreshed, in order to avoid repeated calls to the Twitter Search API.

      $tweetAry = array();
      
      $max_id = "";
      foreach (range(1, 5) as $p) {
        $query = array(
          "q" => "tuaj",
          "count" => 100,
          "max_id" => $max_id,
        );
      
        $results = $toa->get('search/tweets', $query);
      
        foreach ($results->statuses as $i => $result) {
          $tweetAry[] = "[" . $result->user->screen_name . "] " . $result->text;
          $max_id = $result->id_str;
        }
      }
      
      shuffle($tweetAry);
      echo $tweetAry[0];
      
      1. Mike

        Yeah that’s the plan eventually, this is just a mockup for now. How do I link the users screen name to their profile? Thanks again for your help!

        1. techiella Post author

          A URL for user profile consists of “https://twitter.com/” + “screen_name”:

          $tweetAry[] = "[ http://twitter.com/" . $result->user->screen_name . " ] " . $result->text;
          
  7. Todd A. Robinson

    Thank you for this amazing post.
    Is there any way to search Tweets by a Hashtag and reply to the tweet/tweets?

  8. sami

    Thank you for your code,
    but i do not understand the part (search/tweets)
    where shall I place this code?? should it be in the same folder of (twitteroauth.php)
    mine is not working ( Do I need to create “search” or “tweets” folders)!!!

        1. techiella Post author

          Did you read the doc? You don’t need to replace it.
          What error message are you getting?

          1. sami

            Many Thanks for your help,
            yes, I read the doc,
            actually, I found after many trials that it is working on mu local computer but not on my online hosting,
            so I think there is a problem in hosting server configurations,
            do you have any idea?

          2. techiella Post author

            Server configuration could be a problem, but I have no idea without the error message you’ve got.

  9. turan

    I want to use twitter api and show the tweets in a twitter list. I can do it and show latest 20 or 30 tweets. I can define the number but I dont know how to add a “show more” button to tweets. for example I want to show 1000 tweets and in the first place I want to show 10 then a “show more” button. the next 10 tweets will subsitute with the first 10 tweets. is it possible? I’ll apriciate your help. thank you in advance.

    1. techiella Post author

      Yes, it’s possible, but it’s not Twitter API things. You need to use AJAX. If you don’t know about AJAX, you need to study AJAX programming, then you need to implement a “show more” button by yourself with AJAX.

    1. techiella Post author

      You can try with the following query.

        $query = array(
          // tweets from a user "aditya" on Mar 8, 2015.
          "q" => "from:aditya since:2015-03-08 until:2015-03-09"
        );
      
  10. Shikitha

    Hola, excelente informaciĆ³n, no se si tengas una idea de como obtener los twitts por latitud y longitud, y mostrarlos en un mapa de google maps

  11. djex

    I would like to know if it is possible to get Tweets from hashtag without Retweet
    I tried :
    “q” => “#bigtag”,
    ‘include_rts’ => false, // “recent”,
    “count” => 5
    but no way, I get also RT : – (

    TY for your post

  12. Joe Dowes

    Hello, great post!
    Would it be possible to compile the search results into a json file with the geotags?

    1. techiella Post author

      You can convert the search results into JSON data:

      /* $results is a stdClass object. */
      
      // convert stdClass to array
      $ary = json_decode(json_encode($results), true);
      // convert array to json
      $json = json_encode($ary);
      
  13. Glory

    Hi,

    I have tried your code and I got an error states that “Undefined property: stdClass::$statuses” because this line “foreach ($results->statuses as $result)”. Where could be the part I did wrong in this case?

    Thanks!

  14. Nicolas

    Hello,

    Soory for my english,
    I use twitter API to retrieve tweets posted against a hashtag

    Display this , it’s OK and easy,

    $result->user->profile_image_url
    $result->user->name
    $result->user->screen_name
    $result->text

    But I search display information HASHTAGS and MEDIA_URL.

    Thank you for your help
    Nicolas

    1. techiella Post author

      entities variable provides hashtag and media URL.
      $result->entities->hashtags
      $result->entities->media

      foreach ($results->statuses as $result) {
        echo $result->user->profile_image_url . "\n";
        echo $result->user->name . "\n";
        echo $result->user->screen_name . "\n";
        echo $result->text . "\n";
      
        if (!empty($result->entities->hashtags))
        {
          foreach ($result->entities->hashtags as $hashtag)
          {
           echo "hashtag: " . $hashtag->text ."\n";
          }
        }
      
        if (!empty($result->entities->media))
        {
          foreach ($result->entities->media as $media)
          {
            echo "media:        " . $media->media_url . "\n";
            echo "media(https): " . $media->media_url_https . "\n";
          }
        }
        echo "----\n";
      }
      
  15. Philip Chika

    I’ve been trying to use your code to retrieve tweets from search. It works fine until I get to the foreach statement, but then I get errors because the results are not an array but just a big string of data. I don’t see json decode being used here so I don’t understand how the returned twitter data is supposed to get converted to an array. is there some library or class I need to install before this will work correctly?

    1. techiella Post author

      In my environment, $toa->get() returns an object, not json, so no need to decode it.

      I found the following in “lib/twitteroauth.php”.

      class TwitterOAuth {
        ...
      
        /* Decode returned json data. */
        public $decode_json = TRUE;
      
        ...
      

Comments are closed.