This tutorial builds upon my previous two guides for Authenticating a twitter feed using OAuth and PHP (for any public Twitter user timeline) and creating a customised Twitter feed using HTML, jQuery and CSS.
Once you have the Twitter authentication working using OAuth and PHP, altering the PHP query to create a custom Twitter search is pretty straightforward. You can search for any key word, hashtag or Twitter handle you like, or use a combination of these searches terms.
Here’s a demo of a custom twitter search. It is based on mentions/tweets of @timberners_lee (founder of the Internet), the search term ‘netneutrality’ and the hashtag ‘openinternet’.
<?php session_start(); require_once("twitteroauth/twitteroauth/twitteroauth.php"); //Path to twitteroauth library $search = "@timberners_lee OR netneutrality OR #openinternet"; $notweets = 50; $consumerkey = "12345678910"; $consumersecret = "12345678910"; $accesstoken = "12345678910"; $accesstokensecret = "12345678910"; function getConnectionWithAccessToken($cons_key, $cons_secret, $oauth_token, $oauth_token_secret) { $connection = new TwitterOAuth($cons_key, $cons_secret, $oauth_token, $oauth_token_secret); return $connection; } $connection = getConnectionWithAccessToken($consumerkey, $consumersecret, $accesstoken, $accesstokensecret); $search = str_replace("#", "%23", $search); $tweets = $connection->get("https://api.twitter.com/1.1/search/tweets.json?q=".$search."&count=".$notweets); echo json_encode($tweets); ?>
As you can see, the PHP is similar as before but with a new search term and updated API path for the Twitter search (https://api.twitter.com/1.1/search/tweets.json). Obviously you’ll need to replace the 4x access and consumer key/tokens with your own as before. Check that the tweets are displaying before updating the JavaScript.
Copy and paste JavaScript code here
Again the JavaScript is similar to the one we used for the user timeline with a few differences. As the search results return an array of user statuses, we need to drill down an extra level. The line ‘feeds = feeds.statuses;’ does just that.
I have added an optional autorefresh variable – if set to true, the twitter search feed will automatically refresh after the interval time defined by the refreshinterval variable (in milliseconds).
You can use exactly the same HTML structure and CSS from my custom twitter feed tutorial
Notes:
– Twitter only displays searches from the past week or so. Tweets might not appear if you’re searching for an obscure hashtag, phrase or user that doesn’t tweet much.
– Twitter doesn’t make all tweets available for search. View the ‘Why am I missing from search‘ article for more info
Updates:
– 04/08/2013 Added re-tweet indicator and tweet intent actions
– 19/09/2013 Added better hashtag support allowing hashtags to be used in the Twitter search query as well as key words
Creating a Twitter Search & Analytics tool »
I’m running on error :
Fatal error: Class ‘TwitterOAuth’ not found in C:\xampp\htdocs\kejar\code\search\index.php on line 128
Thanks for the above… however, despite the OAuth tutorial working perfectly… when i try the above, i get an error:
{“errors”:[{“code”:195,”message”:”Missing or invalid url parameter”}]}
any ideas?
My code is copy pasted from above, but changed the keys for my OAuth.
Many thanks,
R
Hey thank you very much for this!
I got it working here: [retracted] 🙂
I was wondering if its possible to use a input value from html and use that as a value for the $search
$search = ” “;
as a result: when somebody gives a value to the input they can see related twitter feeds..
can you help me out?
thanks in advance
Aron,
Hi , I ve followed the every step as you said. But tweets are not loading. Its showing only loading animation.
excellent tutorial, thank you!
only one question: how did you create the fade transition for your tweets on this page?
what jquery did you use?
can you post it?
thank you very much!
At first I also got the ‘missing parameters’ error.
It seems to have something to do with your search term?
I think you need at least 2 terms.
For example: “1erang” isn’t working for me, but when I search for “@1erang AND #1erang” I do get results.
I’ve got a problem with the feed not loading.
I started out with your first API 1.1 guide (https://tomelliott.com/javascript-ajax/custom-twitter-feed-integration-jquery/) and this is working fine. Loading tweets without any problems
However, when I swapped the code in get-tweets.php and twitterfeed.js for the code in this search tutorial it stops loading tweets.
I have gone over the code half a million times, and I cannot figure out what’s wrong.
Appreciate if you could help me out.
thank you very much for sharing.
I was able to use https://tomelliott.com/demos/jquery-twitter-feed/js/twitterfeed-main.js
to rotate the excellent works tweets.
excelente aportación, muchas gracias por compartir. pude utilizar https://tomelliott.com/demos/jquery-twitter-feed/js/twitterfeed-main.js
para hacer la trancision de los tweets
Thank you for this tutorial! It’s working like a charm. Any chance you could publish a version that will pull tweets from a Twitter list?
Is it possible to pull tweets from multiple users?
Hi, as per printing the array for the time line
(https://tomelliott.com/php/authenticating-twitter-feed-timeline-oauth/#comment-441789)
This works well on this script;
foreach ($tweets as $item) {
echo $item->text;
}
But for some reason when on search version (i.e $search over $twitteruser) it doesnt return any results.
Am sure its my lack of understanding arrays.
Any help appreciated!
Hi,
Is there a way to display 2 different usernames into one feed? I have clients with specific divisions that have their own twitter accounts but they like to combine them into one feed onto a page.
I am not very good with php (and have some knowledge of javascript), any help would be appreciated.
Thanks for this useful post. For web developers who cater to clients favouring a visually cohesive website design, implementing Twitter Feed authentication can mean more work. Hence, it’s always good to have a step-by-step guide on how it should be done, as reference.
Richard
Hi, how would I access a tweet’s expanded URL? Let’s just say I want to grab the first link on a tweet and find the expanded URL? This is what I tried, unsuccessfully:
var mylink = feeds[i].entities.urls[0].expanded_url;
Any help would be appreciated.
BTW, great post, this has been very helpful.
-@jesseluna
Hi,
thanks for this, I was really stuck trying to connect to the api!
I’m trying to use the statuses/filter url https://stream.twitter.com/1.1/statuses/filter.json
it needs to use POST and pass through the ‘track’ parameter but all it ever returns for me is null, this is the code I am using
$tweets = $connection->post(“https://stream.twitter.com/1.1/statuses/filter.json”, array(‘track’=>’dream’, ‘count’=>10));
Will it work with this do you know?
thanks
Rachael
Hi! I’m trying to follow your tutorial but ím having this problem when y load the page:
OPTIONS file:///C:/Users/Juane/Desktop/BusquedaTweets/php/get-tweets-search.php Origin null is not allowed by Access-Control-Allow-Origin. jquery-2.0.3.min.js:6
XMLHttpRequest cannot load file:///C:/Users/Juane/Desktop/BusquedaTweets/php/get-tweets-search.php. Origin null is not allowed by Access-Control-Allow-Origin.
Do you know what coul it be?
Hi. How do I get the mouseover hover animations/buttons like in your user timeline code? I’ve tried adding the snippet from the .js but apparently I’m not quite savvy enough.
I figured it out. I could share the code if anyone else is interested.
I have another question. How do I modify the feed.js so it includes “Show this photo” links within the tweet and allow the user to enlarge the photo within the feed, basically standard widget behavior? I’m betting it has something to do with:
//Function modified from Stack Overflow
function addlinks(data) {
But I’m not quite sure what to change.
Thanks Tom, I’ve updated the following:
javascript
– line 28 is now ……. $.getJSON(‘…(my website)…../get-tweets search.php?keyword=’+searchterm,
– under var refreshtimer; I’ve added……var searchterm = ;
php
– $search = $_GET[‘searchterm’];
form (on the main page – feed.html)
However it’s not firing for some reason? Thanks for your help.
Hi Sam! For to ask you if you found the way to run the search tweets entering a hashtag from a form?
Thanks in advance
Hi, is it possible to combine the original Twitter user feed with a search for specific hashtags? I currently have a client who we have setup with a feed of their Twitter account on their website but they also want to add hashtags (even if they are not included on their original feed) into the feed on the website.
Thanks!
Mike
Great post!
How can I read the JSON output with a ForEach loop in PHP? I tried several things but can’t get it working…
Hello, nice job with the code above.
It works perfectly with any @whatever, or any keyword, but when the $search var is like this $search = “#seo” , the response is “{“errors”:[{“code”:25,”message”:”Query parameters are missing”}]}” .
Is there a way to make a query search using only hashtags ? Without any user tag or keywords ? Something like this “#seo OR #google OR #webevdoor”.
Many thanks !
Great Work…Congts..Thanks
Hi,
until now I have reach how to show all the tweets I’ve published using mi twitter account using this code:
$connection->get(“https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=”.$twitteruser.”&count=”.$notweets);
But I would like to know if is there any way to show all the tweets that contains my user name @twitteruser and that have published other users.
Thanks a lot
Would you accept a question from a non programmer? I’m designing an app for iPad and your Twitter Feed search matches very well a feature we would like to include. My question is ‘Would your tutorial work for a programmer writing software for an Apple iPad App?
Apologies in advance if this is a dumb question. I’m guessing the software language is different, but maybe the code is a good starting point. Is it worth sharing this link to my agency as proof of concept?
Thanks in advance.
Hi,
I’m trying to use two twitter search feeds on one page and can’t get either to display.
I’ve created 2 different getTweets php files, 2 different JQuery files and directed them to display the tweets in 2 different divs.
Any help would be greatly appreciated.
Thanks,
C
Congratulations for your blog, what you have shared has helped me to know something more about the twitter API and so on JS.
I have a question, how I can do to make a list of users (25 +) search and extract the last twetts concerning a certain hashtag?. I had thought to do that for each of the users make a search, but did as an all in JSON file, then be able to present a single feed?
Once again congratulations for your blog and sorry my English is not very good
Regards !!!!
Hi Tom! How could I do a search for tweets, introducing a hashtag in a text box in the index.html, and upload the results on the same page, ie in the same index.html? Something like this http://emiliocobos.net/demos/buscatweets/
Thank you very much for the help
Hi,
So there is no chance to custom search version ?
I tried to accomplish this with you comment Tom, but there is no go 😉
hi tom
me test :
https://api.twitter.com/1.1/statuses/user_timeline.json
show with :
foreach ($tweets as $item) {
echo $item->text;
}
it work and tnx
but me use :
https://api.twitter.com/1.1/followers/ids.json
work and show with:
echo json_encode($tweets);
but not show with :
foreach ($tweets as $item) {
echo $item->ids;
}
Why result empty ?
Hi Tom and thanks so much for this tutorial.
Is it possible to search only geolocation tweets and extract the coordinates to the tweet?
I have a question, how could save an array of each tweet hashtags?. I have seen that are stored within the json in “statuses.entities.hashtags”. Here should go each index ([0] [1] [2] … [n hashtag]) and go stored in a variable, right? How could I solve it?
Your help is invaluable
hi,
Where you copy and paste php code, before head or in the body,
because JavaScript code don’t work, on my page but it’s ok
for print json_encode
thanks
good afternoon, thanks for the code, I want to just throw a few hashtags counter there, how could it?
I still GET 500 Internal Server Error
I’ve given the relative path and have the twitteroauth library from > https://github.com/abraham/twitteroauth
Anyways, suggestions on passing the json to javascript using jquery?
Thank you for the tutorial. Very straight forward way of doing things. I am using this for a conference app I am building for UT and looking for a way to post from the app to twitter. I would ask for one as clear as your tut, but that may be asking a little much. Any ideas?
I hope one day to be able to offer tuts for people like me that spend countless hours searching the interwebs for things just like this.
Thank you so much for this tutorial, helped me understand a little more…but unfortunately, I get this as a response:
{“errors”:[{“message”:”Could not authenticate you”,”code”:32}]}
My keys are good, double/triple checked…
Do you have any idea of what it could be?
Thanks alot and have a great day!
Ben
Hello Tom,
I am able to get the search-tweets1.1.php file to display the raw output for my search terms, but I am unable to get the final css-styled page to display anything other than the blank white css container with ‘Custom Twitter Search’ as my header. All of my urls seem correct. Any ideas?
there is in error in php file
{“errors”:[{“code”:25,”message”:”Query parameters are missing”}]}
can you please update your code.. i use the same code… and also change the keys but still getting the error