Twitter Search using the Twitter API v1.1 & PHP

I’ll introduce how to run a Twitter search, customize a query and an advanced technique, search & “auto follow”, using the Twitter API and PHP. Example codes in this post work with the version 1.1 of Twitter API. As usual, I’ll use the twitteroauth library by Abraham Williams to make an implementation easy: https://github.com/abraham/twitteroauth.

How to Run a Twitter Search

Code

<?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');

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" => "happy birthday",
);
 
$results = search($query);
 
foreach ($results->statuses as $result) {
  echo $result->user->screen_name . ": " . $result->text . "\n";
}

Output

  $ php search.php
  [fonderlinaz] @bonehatb HAHAHHA happy birthday bone
  [suziejaywill] @JoeyEssex_  can u plz wish my daughter @yasminnlouise a happy 15th birthday for today x x
  [dianndian] Udah kok,, haha  happy birthday ya ta :)) RT @oktathavy: Di delete aja "@dianndian: biasa ta,, ada kenalan di fb minta ketemuan, tapi
  [nastitidwi] RT @ibammargera: Happy birthday @taviash ditunggu ya asupanya haha
  [Runmymind] Happy Birthday to the most beautiful actress in the woooorld:3  #JuliaRoberts
  [aliciaboon] @AlanyaMaisie  happy birthday alanya:D hope you have a good day and see you later! xxx
  [mollybensonx] Happy birthday grandad love you loads xxxxx
  [Sammy_Swales] @ShandyPants_94 Happy Birthday Chris hope u had a great night last night n a great day today x
  [BarrSalihuAhmed] "@sumaiyyaah: Enxx :) @BarrSalihuAhmed: Happy birthday dear, have a blast ! No pun intended @sumaiyyaah"
  [ProudJetsetter] RT @IBeShaunaxo: @ProudJetsetter Happy birthday! Have the best day! (:

Running a Twitter search is very easy with the twitteroauth library. The search function accepts an array of search parameters (I’ll show how to construct it later with some examples) and returns a result in stdClass object.

As shown above, the code outputs usernames ($result->user->screen_name) and tweets ($result->text) found by a search. In this tutorial, I’ll deal with only the two items for output. See https://dev.twitter.com/docs/api/1.1/get/search/tweets in more detail for search result.

Next, let’s see how to customize a query with various examples.

How to Customize a Search Query

Basic Query

A search query is represented with an array. At least, q parameter is required. The following is an example search query for tweets containing “happy birthday”:

$query = array(
  "q" => "happy birthday",
);

$results = search($query);

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

How to Change # of Tweets to Return per Page

The default number of tweets to return per page is 10. The number can be changed with count parameter up to 100. The following is an example for count = 20.

$query = array(
  "q" => "happy birthday",
  "count" => 20,
);

How to Search the Most Recent/Popular Tweets

There are three types of a search result: mixed (default), recent and popular. The default mixed parameter returns both popular and real time results.

The following is an example for recent which returns only the most recent results containing “happy birthday”:

$query = array(
  "q" => "happy birthday",
  "count" => 20,
  "result_type" => "recent",
);

The following is an example for popular which returns only the most popular results in the response:

$query = array(
  "q" => "happy birthday",
  "count" => 20,
  "result_type" => "popular",
);

How to Search Tweets in a Specific Language

The API provides lang parameter to restrict tweets to a specific language, given by an ISO 639-1 code (See: List of ISO 639-1 codes). Here is an example for Japanese with lang = ja.

$query = array(
  "q" => "happy birthday",
  "count" => 20,
  "result_type" => "popular",
  "lang" => "ja",
);

How to Paginate Search Results

A pagination can be implemented with max_id parameter, which returns results with an ID less than (i.e., older than) or equal to the specified ID.

The example code below returns 20 tweets per page and does searches continuously up to 5 pages, so total 100 of the most recent tweets retrieved:

$max_id = "";
foreach (range(1, 5) as $i) { // up to 5 pages
  $query = array(
    "q" => "happy birthday",
    "count" => 20,
    "result_type" => "recent",
    "lang" => "en",
    "max_id" => $max_id,
  );

  $results = search($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
  }
}

Advanced Example – search and auto follow

Finally, I’ll show how to auto-follow a user who tweets with a specific keyword based on search results.

The following example performs “auto follow” for the most recent 20 users who tweet with “happy birthday”:

<?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');

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

function follow($id)
{
  $toa = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET);
  $toa->post('friendships/create', array('user_id' => $id));
}

$max_id = "";
foreach (range(1, 2) as $i) {
  $query = array(
    "q" => "happy birthday",
    "count" => 10,
    "result_type" => "recent",
    "lang" => "en",
    "max_id" => $max_id,
  );

  $results = search($query);
  foreach ($results->statuses as $result) {
    follow($result->user->id);
    $max_id = $result->id_str;
  }
}
Sponsored Links

130 thoughts on “Twitter Search using the Twitter API v1.1 & PHP

    1. techiella Post author

      I’d like to check the code inside foreach(/* what is the code here? */).

  1. prmdherlambang

    Hi, can i have this your full codes? i have try using your steps mentiond above, but give some result, like Fatal error: Class ‘OAuthSignatureMethod_HMAC_SHA1’ not found in C:xampphtdocskejarcodesearchtwitteroauth.php on line 60 .
    I will edit and use my api key. thanks in advance

    1. techiella Post author

      You can use filter:images as part of your query:

      $query = array(
        "q" => "happy birthday filter:images", // query with "filter:images"
        "count" => 20,
        "lang" => "en",
      );
      
      $results = search($query);
      
      foreach ($results->statuses as $result) {
        // "$result->entities->media" contains media info.
        //    e.g. you can get an image url with "$result->entities->media[0]->media_url".
        //    you can see more in detail by var_dump($result->entities->media)
        echo $result->user->screen_name . ": " . $result->text . ": " . $result->entities->media[0]->media_url . "\n";
        // var_dump($result->entities->media);
      }
      
      1. hugo

        Thnx,

        If you want to show instagram photo:

         //Instgram photos
         if(isset($result->entities->urls[0]->expanded_url) && !empty($result->entities->urls[0]->expanded_url)) {
        	if (strpos($result->entities->urls[0]->expanded_url,'instagram') !== false) {
        		echo "entities->urls[0]->expanded_url."media/?size=t'>";
        	}
         }
        
        1. hugo
          entities->urls[0]->expanded_url) && !empty($result->entities->urls[0]->expanded_url)) {
          	if (strpos($result->entities->urls[0]->expanded_url,'instagram') !== false) {
          		echo "entities->urls[0]->expanded_url."media/?size=t'>";
          	}
          }
          ?>
          
      2. Amowogbaje

        I tried changing the count to 133 but the count displayed couldn’t exceed 100
        Is there anything that can be done to this

  2. Hank

    How would you create the array to search for tweets based on location? I’ve tried “geocode” => “xx.xx,xx.xx,xmi” but it doesn’t seem to work.

    1. techiella Post author

      It works for me. I’ve tried a search with the following:

      $query = array(
        "q" => "happy birthday",
        "count" => 20,
        "geocode" => "43.6,39.7302778,10mi" // Sochi, Russia
      );
      
      1. Hank

        Turns out I had to make the second argument negative for some odd reason (even though the actual coordinate isn’t negative). Thanks! Great tutorial.

  3. grillis

    Hi, nice tutorial.
    Can you to show how to search an exact location in bio and /or location fields but that isn’t in tweets?

    I’ve changed only to:
    return $toa->get(‘users/search’, $query);
    but without success.

    Thanks a lot.

    1. techiella Post author

      This code searches users by location “Washington DC” in bio (including location field).
      users/search API doesn’t support a query with geocode.

      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');
      
      function search(array $query)
      {
        $toa = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET);
        return $toa->get('users/search', $query);
      }
      
      $query = array(
        "q" => "Washington DC",
        "page" => 1,
        "count" => 5,
      );
      
      $results = search($query);
      
      foreach ($results as $i => $result) {
        $id       = $result->id;
        $name     = $result->name;
        $scrname  = $result->screen_name;
        $location = $result->location;
        $bio      = $result->description;
      
        echo "$id, $name, $scrname, $location, $bio\n";
      }
      
      1. grillis

        great!
        Just a small thing: if I want to search by location (eg. Washington DC) and between protected accounts only ($result->protected;) how can I edit the code?
        In sql would be like: “… WHERE protected=1 ….”

        Thanks!

        1. techiella Post author

          The users/search API doesn’t support a query like WHERE protected=1, so what you can do is to filter the results with if-statement like this:

          $protected_accnts = array(); // Stores protected accounts
          foreach ($results as $i => $result) { 
            if ($result->protected) {
              $protected_accnts[] = $result;
            }
          }
          
  4. grillis

    and how can I integrate your code?

    $protected_accounts = array(); // Stores protected accounts
    foreach ($results as $i => $result) {
    if ($result->protected) {
    $protected_accounts[] = $result;
    }
    $id = $result->id;
    $name = $result->name;
    echo “$id, $name…”;
    }

    1. techiella Post author
      $protected_accnts = array(); // Stores protected accounts
      foreach ($results as $i => $result) {
        if ($result->protected) {
          $protected_accnts[] = $result;
        }
      }
      foreach ($protected_accnts as $i => $result) {
        $id       = $result->id;
        $name     = $result->name;
        $scrname  = $result->screen_name;
        $location = $result->location;
        $bio      = $result->description;
       
        echo "$id, $name, $scrname, $location, $bio\n";
      }
      
  5. grillis

    i’ve seen. Good.
    Just last things.

    1. I search for (example) “New York” and for protected accounts but I obtain no one result: try yourself. Where is my mistake? I think it’s unlikely that there is not a protected account for a search key so wide.

    2. Searching for accounts (protected or not), the results shown are be always 20 (or less). Why I do not get a maximum of 1000 results as written on dev.twitter.com/docs/api/1.1/get/users/search ?

    1. techiella Post author

      1. The users/search API returns a maximum of 20. So, if you get no one, there is no protected account in the 20 results.
      2. Please read the doc. You cannot get a maximum of 1000, only 20. count parameter has a maximum of 20 per page. You can use page parameter to get next 20 results.

  6. Neil Brazil

    HI,

    I’m using your How to Paginate Search Results example but have an issue.

    The last result item of a page is also being shown as the first item of the next page. Any idea how to get around this?

    Thanks

    1. techiella Post author

      Simple solution would be to skip the first result with “if ($p >= 2 && $i == 0) continue;” (see at line-13).

      $max_id = "";
      foreach (range(1, 5) as $p) { // up to 5 pages
        $query = array(
          "q" => "happy birthday",
          "count" => 20,
          "result_type" => "recent",
          "lang" => "en",
          "max_id" => $max_id,
        );
      
        $results = search($query);
        foreach ($results->statuses as $i => $result) {
          if ($p >= 2 && $i == 0) continue;
      
          echo "[" . $result->user->screen_name . "] " . $result->text . "\n";
          $max_id = $result->id_str; // Set max_id for the next search page
        }
      }
      
  7. shankar

    Hi When I am trying to use sample code I am getting.
    Invalid argument supplied for foreach() in …. on line 24
    I have updatd the twitter auth lib also I am getting same error.
    An foreach loop contains
    foreach ($results->statuses as $result) {
    echo $result->user->screen_name . “: ” . $result->text . “: ” . $result->entities->media[0]->media_url;
    echo “”;
    }

    1. techiella Post author

      That means $results->statuses is not array. I guess $results is null, new TwitterOAuth() failed. Please check your API key is valid or not.

      1. shankar

        How to check whether new TwitterOAuth() is failing or not. Because at first few attempts I got the expected output after few attempts I am getting this error.I am new to Twitter API.Could you please explain me how to debug this issue and solve.

      2. shankar

        And also I am getting twitter object as below
        TwitterOAuth Object
        (
        [http_code] =>
        [url] =>
        [host] => https://api.twitter.com/1.1/
        [timeout] => 30
        [connecttimeout] => 30
        [ssl_verifypeer] =>
        [format] => json
        [decode_json] => 1
        [http_info] =>
        [useragent] => TwitterOAuth v0.2.0-beta2
        [sha1_method] => OAuthSignatureMethod_HMAC_SHA1 Object
        (
        )

        [consumer] => OAuthConsumer Object
        (
        [key] => XXXXXXXXXXXXXXXXXXXXXXXXX
        [secret] => XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
        [callback_url] =>
        )

        [token] => OAuthConsumer Object
        (
        [key] => XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
        [secret] => XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
        [callback_url] =>
        )

        )

        1. techiella Post author

          This debug is another story. You need to authorize your app using OAuth.

          As introduced in this post, the twitteroauth library by Abraham Williams is a solution for OAuth.

  8. shankar

    Hi
    Using API I am getting all the hash tag images tweeted except the ones which are tweeted from recently created twitter account.This is strange but true.
    Is there anything the user has to do in sittings to make it available or by API its the drawback or is it restriction from twitter itself .
    Please provide the any docs related to this if available.
    Thanks in advance.

    1. techiella Post author

      I had faced a similar situation on the official Twitter App for iPhone/iPad, that a search didn’t return tweets by recently created twitter accounts. So, Twitter itself can’t seems to handle it.

      1. shankar

        Thanks for your quick reply. One more thing I want to know, is there any specific time duration after which new account(recently created) tweets will start appearing in search.

        1. techiella Post author

          3 weeks have passed since tweeted, but still not found…
          My conclusion is Twitter search cannot find everything on Twitter.

  9. Ahmad

    Hi,
    How are you? Hope you are fine.
    I am a non techie guy and trying hard but cannot get it working. :(
    I am telling you what i did exactly.
    01. I created a new directory on my linux server.
    02. Download the twitteroauth from github as zip file. Extracted it and uploadded all files to the previously created directory.
    03. I had a previously created twitter application. So i used the CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET from that application.
    04. I used your “Advanced Example – search and auto follow” code and used “require_once ‘twitteroauth/OAuth.php’;” in a newly created php file.
    05. I loaded the php file visiting the direct url but nothing showed up. :(

    Can you give me a step by step guide?
    I will be really happy to get it work. Please shoot me an email with details. Or just comment here. I don’t know if i will get a notification for ur comment.

    My email address is in the “email field” of this reply .

    Thank you in advance for everything.

    Best regards,
    Ahmad

    1. techiella Post author

      > 05. I loaded the php file visiting the direct url but nothing showed up. :(

      The advanced example code shows nothing, just follows users on Twitter. So, you need to check the number of “Following” users increased or not in your Twitter account profile page.

      1. Ahmad

        Thank you for the quick reply.
        I checked the following number using firefox & crome.
        Tried this code with 2-3 app on 2 different server but following did not increase.
        I do not know what i am doing wrong. :(
        Could you please send me an email, so that i can send you FTP access details.
        Or you can send me the files in a zip file in a structured way, so that i can upload them and ready to go.
        May be i am asking too much. I am new to these stuff. :(
        Hope you understand. :)

        Thanks again.

        1. techiella Post author

          Please try the following code on your Web server. If it works fine, you’ll see the following message:

          Hello, World!!
          OK: File found: lib/twitteroauth.php
          OK: Your API call succeeded.
          OK: Your search has a result.
          OK: Your API call succeeded.
          OK: Your search has a result.
          

          **Don’t forget to replace API keys with your keys in the following code. **

          <?php
          
          echo "Hello, World!!<br />\n";
          
          if (!file_exists("lib/twitteroauth.php"))
            echo "Error: File not found: lib/twitteroauth.php<br />\n";
          else
            echo "OK: File found: lib/twitteroauth.php<br />\n";
          
          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');
          
          function search(array $query)
          {
            $toa = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET);
            return $toa->get('search/tweets', $query);
          }
          
          function follow($id)
          {
            $toa = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET);
            $toa->post('friendships/create', array('user_id' => $id));
          }
          
          $max_id = "";
          foreach (range(1, 2) as $i) {
            $query = array(
              "q" => "happy birthday",
              "count" => 10,
              "result_type" => "recent",
              "lang" => "en",
              "max_id" => $max_id,
            );
          
            $results = search($query);
          
            if (!$results)
              echo "Error: Your API call failed.<br />\n";
            else
              echo "OK: Your API call succeeded.<br />\n";
          
            if (empty($results->statuses))
              echo "Warning: Your search has no result.<br />\n";
            else
              echo "OK: Your search has a result.<br />\n";
          
            foreach ($results->statuses as $result) {
              follow($result->user->id);
              $max_id = $result->id_str;
            }
          }
          
          1. Ahmad

            Getting a 500 Internal Server Error. :(
            Here is a screenshot of my files http://i.imgur.com/2gq8aHv.jpg
            “1.php” contains the code that you provided. Here http://i.imgur.com/CC3nlVn.jpg
            Please note that i did not modify any other files in the directory than “1.php” .
            Did not find “lib” directory, so used “twitteroauth/twitteroauth.php” .

            I do not what i am doing wrong. :(

            You are trying hard to help me but may be it is my bad luck that it is not working. :(

          2. techiella Post author

            If the following simple code also gets an error, your server environment is not ready to execute a PHP code.

            <?php
            echo "Hi";
            

            You need to check an error log on your Web server or ask your server admin.

  10. Ahmad

    I seriously tested your code

    <?php
    echo "Hi";

    And it worked.

    I think server environment is ok.
    I have 5 domains/sites (, opencart & wordpress) and a few sites on subdomains including a simple twitter app to schedule tweets.

    If you don't mind, Can i send FTP access information to you?
    My email address is contact(at)shibbirahmad(dot)com

    Sorry for asking too much .
    Please send me an email.

    1. techiella Post author

      OK. The 1st code of this article worked fine.
      So, the advanced example code and the test code “1.php” should work fine.

      The following code is logically the same with the 1st code of this article. This code should work fine.
      If it worked fine, uncomment the line-29, which is almost the same with the advanced example code.

      <?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');
       
      function search(array $query)
      {
        $toa = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET);
        return $toa->get('search/tweets', $query);
      }
      
      function follow($id)
      {
        $toa = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET);
        $toa->post('friendships/create', array('user_id' => $id));
      }
      
      $query = array(
        "q" => "happy birthday",
      );
        
      $results = search($query);
        
      foreach ($results->statuses as $result) {
        echo $result->user->screen_name . ": " . $result->text . "\n";
        //follow($result->user->id);
      }
      
      1. Ahmad

        Thank you very much for the code.
        You are more than helpful here.
        Your previous code worked when i removed this

        echo “Hello, World!!\n”;
         
        if (!file_exists(“lib/twitteroauth.php”))
          echo “Error: File not found: lib/twitteroauth.php\n”;
        else
          echo “OK: File found: lib/twitteroauth.php\n”;

        Your last code worked too.

        Cannot thank you enough for this.

        Did set up a cron job with it. :)

  11. Ahmad

    Hi, did you think of re tweeting searched tweets somehow?
    I searched on google and found this http://goo.gl/ZqkpGV
    Could you please take a look on it?
    It is pretty old but though.

    Thanks again.

  12. Ahmad

    Hi,
    How are you? Hope you are fine.
    I am trying to post tweets and tried customizing your code.

    Here is what i tried.


    post('statuses/update', array('status' => $message));
    }

    // Set status message
    $msg = 'This is a tweet to my Twitter account via PHP.';

    // Check for 140 characters
    if(strlen($msg)

    Could you please guide me to the right way to do this.

    Thank you in advance.

      1. techiella Post author

        You (Ahmad, rj, Todd A. Robinson) are the same person?

        Anyway, here is an example for reply.

        <?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');
         
        function search(array $query)
        {
          $toa = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET);
          return $toa->get('search/tweets', $query);
        }
         
        function follow($id)
        {
          $toa = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET);
          $toa->post('friendships/create', array('user_id' => $id));
        }
        
        function reply($screen_name, $reply, $in_reply_to_status_id)
        {
          $toa = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET);
          $toa->post('statuses/update', array('status' => "@$screen_name $reply", 'in_reply_to_status_id' => $in_reply_to_status_id));
        }
        
        $max_id = "";
        foreach (range(1, 2) as $i) {
          $query = array(
            "q" => "happy birthday",
            "count" => 10,
            "result_type" => "recent",
            "lang" => "en",
            "max_id" => $max_id,
          );
         
          $results = search($query);
          foreach ($results->statuses as $result) {
            follow($result->user->id);
            reply($result->user->screen_name, "this is a reply message", $result->id_str);
            $max_id = $result->id_str;
          }
        }
        
        1. rj

          thank you it works great was wondering why when the script replys to the tweets why does it use @2394500043 instead of the username

          1. techiella Post author

            It’s strange. You don’t read the code at all?

            As you can see $result->user->screen_name at line-40, the code uses “username”, otherwise a reply doesn’t work properly.

  13. Thamaraiselvam

    Thank you so much sir its working fine but i get sometimes error like
    this Fatal error: Maximum execution time of 30 seconds exceeded in C:\xampp\htdocs\test\twitter_search_example\lib\twitteroauth.php on line 225

    and How to search based on time for ex from past half and hour !

  14. Thamaraiselvam

    sir !

    Can i search tweets based on date ??
    for ex: Last one week ? and can i segregate them based on date??

    how do i get tweet time?

    please reply me !

  15. Thamaraiselvam

    Sir ,

    I have a doubt ! this code only searches my friendsmy friend(My followers or i’m following ) tweets only or from the public tweets?
    because if i search like nokia or any other keyword am getting just 15 to 20 tweets only !
    is there any way to search tweets who are not my friend(My followers or i’m following ) ?
    i mean from the all the tweets world wide !

    1. techiella Post author

      > this code only searches my friendsmy friend(My followers or i’m following )
      No, the code doesn’t do that. It’s very strange.

  16. Ree3

    Hello, World!!
    OK: File found: lib/twitteroauth.php
    OK: Your API call succeeded.
    Warning: Your search has no result.
    Notice: Undefined property: stdClass::$statuses in /home/d/public_html/RTES/tse/search.php on line 58 Warning: Invalid argument supplied for foreach() in /home/d/public_html/RTES/tse/search.php on line 58 OK: Your API call succeeded.

    Why I can’t get any results from search? Code is the same, didn’t change anything.
    “q” => “happy birthday”,

    1. techiella Post author

      Are you sure that the API keys you’re using (at line 4-7) are correct?

      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');
      
    1. techiella Post author

      Twitter provides users/search API. Here is an example code to search Twitter bios only with “developer”:

      <?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');
      
      function search(array $query)
      {
        $toa = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET);
        return $toa->get('users/search', $query);
      }
      
      $query = array(
        "q" => "developer",
        "page" => 1,
        "count" => 10,
      );
      
      $results = search($query);
      
      foreach ($results as $i => $result) {
        $id       = $result->id;
        $name     = $result->name;
        $scrname  = $result->screen_name;
        $location = $result->location;
        $bio      = $result->description;
      
        if (preg_match('/' . $query["q"] . '/i', $bio))
        {
          echo "id:$id, name:$name @$scrname, loc:$location, bio:$bio\n";
        }
      }
      
  17. raza

    I am unable to get tweets through date. I want to get all tweets of ipl 2014. IPL was played in june july last year. this is query i am sending
    $query = array(
    “q” => “happy birthday”,
    “until”=>”2014-08-01”,
    );

    but no result obtained.But if i only pass query i have recent tweets.I need all tweets from specific date.Please help me.

    1. techiella Post author

      You can use until option.

      $query = array(
        “q” => “happy birthday until:2014-08-01”,
      );
      
  18. Amowogbaje

    I change the count parameter to 221 but the tweets generated didn’t exceed 100
    I want to get tweets that are more than 100 in number please how do I go around this

  19. vinod

    hi!!
    I am a new bee in twitter programming. For my project work, I want to analyse the twitter #tag public streams like #swineflu. The tweets I want to view on to map and to analyse.
    I dont have a public URL(domain). I am trying this on localhost. When I am trying the simple query of reading tweets from account using Aauth, neither the program is giving any error nor I am able to fetch output(Json).
    Can localhost be used for running the appliction? What I am missing/
    Any help in this regard is appreciable.
    thanks in advance

    1. techiella Post author

      localhost (you mean your PC?) should be OK.

      Please make sure your Twitter API key is correct if you cannot get a result.

    1. techiella Post author

      Here is an example code which gets up to 100 retweets of a tweet and follows the retweeters.

      $toa = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET);
      
      // Get retweets.
      // (twitter.com/POTUS/status/600324682190053376 - the 1st tweet by President Obama.)
      $retweets = $toa->get('statuses/retweets', array('id' => '600324682190053376', 'count' => 100));
      
      foreach ($retweets as $retweet)
      {
        // Follow a retweeter.
        $toa->post('friendships/create', array('user_id' => $retweet->user->id));
      }
      
        1. Shibbir

          This code worked!
          I hope you make it get more than 100 retweets of a tweet and follow the retweeters using pagination or something. I read on that doc that cursor Parameter can be implemented.
          Again seeking your help.

          1. shibbir

            Hi,
            I am wondering if it is possible to get the last ten tweets of a twitter user and then follow the retweeters of those ten tweets. This way total follow will be below 1000 and avoid twitter restrictions.

            Thank you in advance.

            Regards,
            Shibbir Ahmad

          2. shibbir

            Thank you for the quick reply.

            Could you please provide me the code which can perform the task i mentioned ?

          3. shibbir

            Thank you.
            But i have no idea how to make these 2 codes work together.
            I really need your help.
            Could you plz send me an email showing me the way to do it?
            I combined those two codes but it did not work. :(

  20. Hemant Bansal

    Hi there,

    i just want to know if there any method to get the time of post(tweet) using this code..

    1. techiella Post author

      You can get the time of tweet with created_at.

      echo $result->user->screen_name . ": " . $result->text . " (" . $result->created_at . ")\n";
      
  21. wuwu

    hello, is it possible to search tweet from a user with a specific word? like twitter advanced search. is it available in twitter api?i’ve been searching but still no luck.

    1. techiella Post author

      You can do that with the from: option. The following tries to search “people” from President Obama(@POTUS).

      $query = array(
        "q" => "people from:POTUS",
      );
       
      $results = search($query);
       
      foreach ($results->statuses as $result) {
        echo $result->user->screen_name . ": " . $result->text . "\n";
      }
      
  22. Lucas Melo

    Hi, it is possible to do a search with two or more words , showing only the tweets with two or more search words ? ( they do not need to be together )
    I do some searches with 100 tweets and sometimes many of these tweets have only one of the search words .
    Thank you!

    1. techiella Post author

      I have no idea. Twitter search returns something strange results.

      For example, Twitter search with “Google” and “Microsoft” returns a tweet which contains “Google” but also contains “Windows” instead of “Microsoft”. So, I guess Twitter search replaces some words with the other words automatically.

  23. Lucas Melo

    I’m doing research for college, where I need to do searches using the twitter API using the word “twitter” and some other keywords, to do some analysis. However, the twitter API returns me words without the word ” twitter ” , I think this happens because the URLs ( links or images) of tweets that are replaced by “t.co” links.
    It is possible to make the twitter API to return the original links during the search ?

    Thank you!

  24. lildiya

    sir, i am lack knowledge on php. i am in the progress of developing my api. but i have an error at line 129 for the file TwitterOAuth.php.
    Can you help me to solve this problem?

    Parse error: syntax error, unexpected ‘[‘ in C:\xampp\htdocs\twtroath_master\src\TwitterOAuth.php on line 129

    public function oauth($path, array $parameters = [])

    1. techiella Post author

      I guess the PHP version on your system is 5.3 or older. The latest TwitterOAuth library requires PHP 5.4+.

      1. lildiya

        Thank God! it works after i install the new php version. thank you sir!
        Can i ask, how can i insert those api results into my database? at which statement do i need to edit and make sure that every single of those data is inside the database?

        1. techiella Post author

          You need to learn MySQL. You can find the other websites for that, with google search by keywords: “PHP PDO MySQL”.

  25. David

    3 Quick Questions:

    1. Can you post a download link to your most updated version of the “search and auto follow” code? You posted a link to a zip file a couple years ago, just wasn’t sure if that’s still working and the most updated code.

    2. What happens if you’re already following a user who comes up in the search results? Does your script still send an API command to try to follow that user?

    3. Could we search for multiples keywords at the same time like this: “keyword1 OR keyword2 OR keyword3”?

    Thanks so much!

      1. David

        Wow you reply fast!

        I’ve tried looking for this in the Twitter API docs and couldn’t find anything definitive. Perhaps you’ll know: If your script tries to follow a user that’s already being followed, does that count against your API/follow limits?

        My main concern is whether Twitter would get upset about someone trying to follow hundreds of accounts per day that they were already following lol :)

          1. David

            Hmm have you found any way around that? Such as checking to see if you’re already following a user before sending the request?

            Or perhaps a script that will get a list of all your followers and insert them into a MySQL database (as long as they don’t exist there already). Then the script could check the database to see if that user is already being followed and skip it…

  26. vijay gupta

    Hello,

    Please anyone can navigate me that how can i filter tweets by video ?
    Mean i wants to show only those tweets whose have Video.

    Thanks

    1. techiella Post author

      The following code tries to search tweets which contain “cat” related videos. A tweet with video contains a string “video” in its expanded_url.

      $max_id = "";
      
      foreach (range(1, 5) as $p) { // up to 5 pages
        $query = array(
          "q" => "cat",
          "max_id" => $max_id,
        );
      
        $results = $toa->get('search/tweets', $query);
      
        foreach ($results->statuses as $i => $result) {
      
          if (empty($result->entities->media)) continue;
      
          foreach ($result->entities->media as $media)
          {
            if (preg_match('/video/', $media->expanded_url)) // the tweet contains video?
            {
              echo $result->user->screen_name . "\n";
              echo $result->text . "\n";
              echo $media->expanded_url . "\n";
            }
          }
      
          $max_id = $result->id_str; // Set max_id for the next search page
        }
      }
      
      1. vijay gupta

        Thanks for reply,

        Actually i want to show tweets by Trends.

        In my script i am getting all trends and then i used foreach loop to for trends and inside loop i am getting tweets (whose have video).
        So in my script i am putting trend name is “q” But you putt
        “q” => “ZoomTv”, // ZoomTv is my trend

        I tried your script but i am not getting “video” keyworkd in my all data. I checked it by print array.

        Please give me solution.

        thanks

  27. vijay gupta

    Hello,

    Thanks for quick reply

    Actually i need mp4 format, Is there have any other way to get mp4 format.

    Actually i have to show these videos somewhere that is why i need.
    Please help,
    Thanks

    1. techiella Post author

      A possible way is to use C#, .NET WebBrowser control and Javascript.

      1. Invoke Twitter API calls with C# and get video tweets (expanded_url) with Twitter search.
      2. Open the expanded_url page with .NET WebBrowser control.
      3. Execute a javascript code, which searches a DOM element containing a direct link to mp4 video file, on the page with the WebBrowser control.

        1. techiella Post author

          Again, Twitter search result doesn’t provide a direct link to mp4 video file.

          So, you need extract it by yourself with HTML DOM parsing on the page “https://twitter.com/…/photo/1”, which can be done with C#, .NET WebBrowser control and javascript code.

  28. guest

    hi! I’m new with twitter API and abraham’s code. I would like to ask how can we get some user’s basic information? Thanks

    1. techiella Post author

      GET users/show returns a variety of information about a user.

      See the following API doc for details:
      https://dev.twitter.com/rest/reference/get/users/show

      $toa = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET);
      
      $screen_name = 'TwitterEng';
      $info = $toa->get('users/show', array('screen_name' => $screen_name));
      var_dump($info);
      
  29. barney

    I just wanna make sure, that:
    1) count limitation is just 100 so we can use pagination for generate more than 100 tweets.
    2) It will return the result for max 7 days ago.
    3) Then, maximum search limited to 1500 tweets.

    but when I change count to: 100 and range (1,16), I still can get the result more than 1500. Am I wrong for the statement above?

  30. barney

    and I would ask next question,
    when I implement this:

    if ($p >= 2 && $i == 0){
    continue;
    }

    I got the result -1, for example when I have count = 100, and range (1,2) this return me 199 data not 200. What should I do? :’)

    1. techiella Post author

      I think you just don’t understand what the “continue” statement does…

      1. barney

        that mean skip the first ryt? I just have no idea how to get the same amount of result with continue statement… (without minus 1 result)

Comments are closed.