So for today’s blog post I am going to show you how you can use jQuery, PHP and a little ajax to connect up to the Twitter API and return results. I’ll cover off unauthenticated calls today to the search API, and follow up with the authenticated piece a little later, so watch out for that!
PHP using cURL
So, in order for us to talk to the Twitter API, we need to use cURL. This isn’t a hard and fast rule, but it sure does make our lives easier. The cURL library should be installed as part of your PHP installation, but do check.
cURL allows us to make a simple call to the Twitter API, and grab some results back if necessary. I’ll be using XML to return results for this demo, but you can use JSON if you want. Anyway, without further ado, here is a nice piece of PHP code to talk to the Twitter Search API – so create a file called getSearch.php :
<?php
$query = $_POST['query'];
$curl = curl_init();
curl_setopt ($curl, CURLOPT_URL, "http://search.twitter.com/search.atom?q=" . urlencode($query) . "&amp;amp;rpp=10");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec ($curl);
curl_close ($curl);
header('Content-Type: application/xml; charset=ISO-8859-1');
print $result;
?>
So, lets quickly explain this. The PHP script will take POST data, in this case a query, and send the query to the Twitter Search API. The Twitter API is also taking an rpp parameter, which is the number of results to be returned. It will then return XML, and also print it out as a valid XML document. Job done. Obviously there is no error handling, this is the bare bones – I will let you deal with all of that!
The jQuery
The jQuery side is also pretty straight forward… It’ll do an ajax post call to our PHP script, and go through the XML returned and paste it into a location in your DOM HTML. So, create a controller.js file and put this code into it:
var timer;
$(document).ready(function() {
getSearch();
});
function getSearch()
{
clearTimeout(timer);
var results;
var theQuery = "stevereynolds";
$.post("/getSearch.php", {query: theQuery}, function(xml){
$('entry',xml).each(function(i){
var title = $(this).find("title").text();
results = title + "<BR>";
});
$("#container").html(results);
});
timer = setTimeout('getSearch()', 30000);
}
So this code sets the query parameter to “stevereynolds”, makes an ajax post to our getSearch.php file, and then runs through the returned XML. It firstly searches for the “entry” node, and then the “title” parameter as part of each “entry” node in the XML. Lastly, it applies the results to a container in your DOM called “container”. This function also runs every 30 seconds, see the setTimeout for that part.
Putting it all together
So, putting it together is pretty darn easy. Create an HTML page in the same directory as all of the above, with the following:
<HTML> <HEAD> <script src="jquery-1.3.1.js"></script> <script src="controller.js"></script> </HEAD> <BODY> <DIV id="container"></DIV> </BODY> </HTML>
Thats it! When you load your HTML it will call the controller.js -> which in turn will call the javascript function getSearch() to return Twitter Search API results every 30 seconds.
Feel free to download this code and reuse as you want. As I said, it’s very simplistic – so go ahead and adapt this with lots more jQuery lovelyness! Feel free to share back your fine work! Also see my new article discussing making authenticated calls to the Twitter API.
|
|
|
|
Similar Articles:
Twitter API calls in the browser with JSON and jQuery
Sending Authenticated Data to the Twitter API
Authenticating Twitter API calls with PHP & jQuery
Tutorial: From PHP to XML to jQuery and Ajax
Using jQuery and Ajax To Create PHP Sessions












Hi, nice tutorial, but I’m curious. Why not use $.getJSON with a callback function (you can use it cross domain), and remove the PHP entirely? As an added bonus, you won’t have to deal with XML, and it will work without cURL too.
Hey – thanks for the great feedback – I haven’t played with JSON but this will be even easier it sounds… thanks!
Hi Steve, hope you don’t mind, but I wrote up a quick post on $.getJSON! Looking forward to your post on authenticated use of the API!
All good my friend! I’ll post an authenticated article over the weekend/Monday
Great article Steve. Thanks for sharing.
Look forward to reading the post on authenicated access.
Thank you
API calls using authentication will be tomorrow hopefully!
I just blogged about this jQuery plugin for displaying Twitter feeds. It’s quite useful and if nothing else provides a great example of how jQuery can be used to parse RSS feeds. Great work!
http://blarnee.com/wp/a-jquery-and-twitter-plugin/
Steve, in the example given how can you STOP the timer !
The timer is stopped by this piece of code: clearTimeout(timer);
You can call that at any point and it will cancel the timer.
HTH. Steve
hey steve-
how would i query multiple terms in the var theQuery = row?
Hey,
I’m going to play around with this, but I would like to know the same thing as shep.
I’d like it to return results for any of the terms I list. Is that possible?
Hi Steve, thanks for this great little add-on, but I was wondering, I’ve set the code to only pull one result per query, is there a way to clear the past query before writing the new results? I would like to put the results in a small space that would only hold one results at a time. Thanks,
Steve
Hi steve,
To clear the container, simply do this: $(”#container”).html(”");
This will empty it of any code, ie your previous query result…
Shep / Nick,
Can you not just set the query to multiple terms? var = “stevereynolds jquery”; ?
Steve,
Thanks for the help, you’re right it does clear the previous posts, but when it query’s it again, it still returns ALL of my previous posts, I want it to pull ONLY my last post.
Does that make sense? I hope I’m explaining my wants clearly enough.
Thanks again,
Steve
I just tried thing and I get no results when viewing the html page on my web server. I know there are results for my search term. Any ideas?
thanks for the tutorial its what i was looking for works perfect can you help me here please how i can get the name (screen name) or other tags using your code ?
thanks in advance
This part : $(this).find(”title”).text()
Gets the “title” node from the XML that the Twitter API returns.
There should be a “name” node in the returned XML, so just update the jQuery code…
anybody know how to get it to display the username for each tweet result with a linkback to that twitter users profile?
Thanks for the article, just what I was after by the look of it. Is there a demo of this to see how it works?
Hi Steve,
I downloaded you code and started testing it, but it doesn’t do anything! I didn’t alter anything yet. What’s going wrong?
http://www.fabiandesign.nl/twitter/index.html
good stuff steve.
quick not for those geting the demo code on this page to run:
the current code in controller.js will only display one of the results retrieved as-is, so in order display them all simply change the results assignation line to append rather than overwrite.
results = title + “”;
to
results += title + “”;
best,
rob ganly
steve this was so helpful. I just wanted to tip my noob hat.
Please help!
I run this code , when i run getsearch.php i get an error . you must enter a query.
what i am doing wrong.
Thank You!
David
Hello, about php, twitter api and xml, use SimpleXML to read the content in $result.
$result is an array so treat it like one. Use (string) to show the results
If you only use
echo $result->user->id or something, the result won’t show up and the thing missing is (string)
Lo descubri tratando de usar la api de twitter con php
Espero les sea util (i hope this can be useful)
@chepe263
Thanks for the helpful addition
If you want to grab more information, show the image of the user and have multiple tweets**, put the following in the getSearch() function (**only for multiple tweets do you need the vars as Arrays):
And then there is the function that grabs the XML data (Once again if you have multiple tweets then you put the [i] after the variable names, otherwise you can drop it):
$.post("getSearch.php", {query: theQuery}, function(xml){ $('entry',xml).each(function(i){ title[i] = $(this).find("title").text(); name[i] = $(this).find("name").text(); uri[i] = $(this).find("uri").text(); image[i] = $(this).find("link[rel='image']").attr("href"); id[i] = $(this).find("id").text();Then this code goes where the results are, outside the $(’entry’,xml).each(function(i)
results = "<a href='" + uri[0] + "' rel="nofollow">" + name[0] + "</a>" + " " + title[0] + ""; results2 = "<a href='" + uri[1] + "' rel="nofollow">" + name[1] + "</a>" + " " + title[1] + ""; results3 = "<a href='" + uri[2] + "' rel="nofollow">" + name[2] + "</a>" + " " + title[2] + ""; $("#container").html(results); $("#container2").html(results2); $("#container3").html(results3);Make sure to add the other container divs to the HTML.
Enjoy!
Heya… what about error handling? JSONP is a real B when it comes to *real* error handling.
Ohhh, set a timeout he says. Nope. Kinda shaky.
i like script thank.
hi
when i download your script and upload in to my host its not working how can use this script thanks
http://s-series.co.in/twitter/ this is the url where i uploaded files
Hello I am so delighted I found your blog, I really found you by mistake, while I was looking on Yahoo for something else, Anyways I am here now and would just like to say thanks for a tremendous post and a all round entertaining blog (I also love the theme/design), I don
i always update my Twitter and i love to twitter my daily activities to my friends and loved ones. i also maintain a personal blog for entries which requires more detail.
Thanks for the info. I couldn’t locate something like this anywhere.
when i download your script and upload in to my host
hi
when i download your script and upload in to my host its not working how can use this script thanks
http://frontlinedogs.org this is the url where i uploaded files