Do you want to implement Twitter Search API on your website? Twitter REST APIs provide a way for developers so they can search tweets or users by writing some piece of code.
For our applications, we are using the TwitterOAuth library. Read our post HOW TO SEND A TWEET ON TWITTER WITH PHP, where we write about the installation of this library.
Twitter mentioned that Search API is focused on relevance and not completeness. This means that some Tweets and users may be missing from search results. Despite this, you can get sufficient search results.
How To Search Tweets Using API
Once you installed the TwitterOAuth library, you are able to search tweets through REST APIs. To search tweets, Twitter provided an endpoint search/tweets. We will use it in seconds. To proceed I assume that, you have set up your Twitter application and you have your application keys with you.
We need to create an object from the class TwitterOAuth. You need to add the below code for it.
require('vendor/autoload.php');
use Abraham\TwitterOAuth\TwitterOAuth;
$connection = new TwitterOAuth('YOUR_CONSUMER_KEY',
'YOUR_CONSUMER_SECRET', 'YOUR_ACCESS_TOKEN',
'YOUR_ACCESS_TOKEN_SECRET');
Once we instantiate the connection object, we are able to use REST API’s endpoint. Below is the code for our endpoint ‘search/tweets’.
$arr_tweets = $connection->get("search/tweets", [
"q" => "@WordPress", "result_type" => "recent",
"count" => "15", "lang" => "en"]);
The above method will return recent 15 tweets which are written in the English language. To read more about parameters, you can read Twitter developer’s documentation GET search/tweets.
How To Search Users Using API
You can search users in the same way as you search tweets. The only difference is in some parameters and in the endpoint. For user search, we use the endpoint ‘users/search’. You can read more about this on GET users/search
Let’s add some code to it. For example, I want to search for users with the name ‘Matt’. So my code would be as below.
$arr_tweets = $connection->get("users/search", [
"q" => "Matt", "count" => "15"]);
The above code will return 15 users with the name contains ‘Matt’. You can apply more parameters to the search function as provided in the Twitter developer documentation.
I hope you understand how to use Twitter Search API. For any questions or suggestions please leave a comment below.
If you liked this article, then please subscribe to our YouTube Channel for video tutorials.