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" );
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
Yes, it’s possible. You can use
since
anduntil
options. The following code searches tweets tagged with “#Niche” since 5/17 until 5/19.That’s amazing! Thanks for your help :)
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
You mean user profile image? Please try the code on #comment-3558.
Theusers/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:ou will get a result like the following, that contains profile image URLs for users who have a tweet found by the search.Thank you very much !
Very helpfull !!
Excuse me but i’ve an other question.
How to put in relation the tweet and the profil pic ?
Thank you a lot !!
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”;
}
?>
I simplified the previous code (
users/lookup
related code was not needed). Please try this one:How do I get the keys and tokens? Why can’t someone make a complete tutorial that includes EVERYTHING? Fucking Twitter API…
Short tutorial:
Then you can get the following 4 things:
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";
}
What output do you expect?
I did “copy & paste” your code and executed it. I got the following tweet.
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
}
}
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.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!
A URL for user profile consists of “https://twitter.com/” + “screen_name”:
Thank you for this amazing post.
Is there any way to search Tweets by a Hashtag and reply to the tweet/tweets?
See “reply” function at: http://techiella.x0.com/practice-of-programming/twitter-search-using-the-twitter-api-php/#comment-5248
Thank you, you really helped me.
Is there any implementation of that in AJAX?
I have no code, haven’t tried in Javascript. But Twitter Dev provides a list for Twitter libraries: https://dev.twitter.com/overview/api/twitter-libraries
The following library, TwitterJSClient, would be helpful?
https://github.com/BoyCook/TwitterJSClient
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)!!!
search/tweets
is, not directory, an API call with the twitteroauth lib.See: https://github.com/abraham/twitteroauth
Thanks for your reply,
so shall I replace (search/tweets) with:
https://api.twitter.com/1.1/search/tweets.json
??
because I am having an error message on this line of code!!
Did you read the doc? You don’t need to replace it.
What error message are you getting?
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?
Server configuration could be a problem, but I have no idea without the error message you’ve got.
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.
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.
how can i get timeline of a user for a whole day.
You can try with the following query.
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
See: http://techiella.x0.com/twitter-search-using-the-twitter-api-php/#comment-1106
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
Found :
“exclude” => “retweets”
TY
Hello, great post!
Would it be possible to compile the search results into a json file with the geotags?
You can convert the search results into JSON data:
where can I get lib/twitteroauth.php ? because the files on the website abraham changed
You can download Twitter bot code, which contains lib/twitteroauth.php, from “How to Auto Follow on Twitter by Twitter API v1.1 & PHP”.
article link: http://techiella.x0.com/practice-of-programming/how-to-auto-follow-on-twitter-by-twitter-api-php/
direct link: http://techiella.x0.com/practice-of-programming/wp-content/uploads/2012/10/source-1.1.zip
Hi,
where i can download lib/twitteroauth.php
thanks
direct link: http://techiella.x0.com/practice-of-programming/wp-content/uploads/2012/10/source-1.1.zip
article link: http://techiella.x0.com/practice-of-programming/how-to-auto-follow-on-twitter-by-twitter-api-php/
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!
Your API keys are correct?
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
entities
variable provides hashtag and media URL.$result->entities->hashtags
$result->entities->media
Thank you so much Techiella ! Very good, It’s ok.
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?
In my environment,
$toa->get()
returns an object, not json, so no need to decode it.I found the following in “lib/twitteroauth.php”.
Thank you! Works perfect.