Digg API: Grabbing a Random Digg Story with PHP
I read about the Digg API the other day, and I thought it was about time I played around with it.
There is a ton of cool stuff you can do with this. Basically, you send a request to the Digg server and it sends back whatever kind of information you want - category names, recent diggs, recent stories, archived stories, etc. You can read through the API to see everything you can do.
For now, we’ll focus on one nifty little trick - grabbing a random story from a given topic.
Digg API Basics: How It Works
Before we can build our script, we need to know the basics of how the Digg API works.
Your script sends an HTTP GET request to the Digg server. This has three major parts. If this is valid, the server sends you a response in one of several designated formats. You can then parse it into use-able information and display it on your site.
The basic parts of the request are…
- Base Digg URL: http://services.digg.com
- An Endpoint: i.e. /stories/topic/programming - this determines the type of information you’re getting back
- A query string: i.e. ?count=5&offset=20
For this tutorial, we’ll be working with the “Programming” topic because, well, it works with my site. You can look at the list of topics on the API page and tailor this to your needs.
Therefore the URL we’ll be accessing is: http://services.digg.com/stories/topic/programming
What Goes In the Query String
To go along with this, we’re going to have to build a query string. There are a few required elements (appkey, type) and some optional ones that we’ll also use (count, offset).
“appkey” is basically an ID tag associated with your application. Digg uses this for statistical purposes. You can set this equal to the URI of your website.
“type” describes the type of response you’ll get. There are four response types, of which two are applicable for use in a PHP script. We’re going to focus on the XML response and use SimpleXML to parse the information. Therefore type should be set to ‘xml.’
“count” tells the server how many stories we want to fetch. “offset” tells the server how many stories to skip before it starts fetching them. The “offset” is going to allow us to fetch a random story.
Building the Query String
So how do we build the query string? First, we need to turn each of our values into a parameter in the format key=value. The value must also be url encoded. Here’s how we do that in php.
$appkey = 'http://www.earn-web-cash.com'; $appkeyParam = 'appkey=' . urlencode($appkey);
We can then string together all these variables with ampersands (&) in between. We then place a ? in the beginning of the query string, attach it to our URL, and we’re good to go.
I wrote a short function I use to automatically build the query string from an array of values. I create an empty array, store the value with a key equal to its parameter name, and then pass it through the function. The function returns the full query string for me to use.
// Example array: // $params['appkey'] = 'http://www.earn-web-cash.com'; // $params['type'] = 'xml'; function buildQuery ($args) { $query = '?'; foreach ($args as $key => $val) { if ($query != '?') { $query .= '&'; } $query .= $key . '=' . urlencode($val); } return $query; }
One other minor task we need to do is set up a “user_agent” for PHP. The Digg server wants to know who’s accessing it, so you need to define a “user_agent” value for your instance of PHP with the ini_set command. You can call your application whatever you want, but it usually follows the format - Name/Version.
ini_set('user_agent', 'RandomDiggStory/1.0');
Firing Off the Request and Getting a Response
We should now be able to send our request, get a response, and use some information.
To get a random story, we’re actually going to have to send two requests. The first is going to allow us to find out how many stories exist in the topic. The second will actually fetch a random story.
To find out how many stories exist in the topic, we’re going to create our request with the following information. The appkey doesn’t matter, the type will be xml, the count will be 0, and the offset doesn’t matter.
Once we build the entire url with the query string, we open that location with simplexml_load_file - and the response will automatically be placed in a SimpleXML object for us.
$params = array(); $params['appkey'] = 'http://www.earn-web-cash.com'; $params['type'] = 'xml'; $params['count'] = 0; // We don't need an offset for this one $query = buildQuery($params); $url = 'http://services.digg.com/stories/topic/programming'; $reqUrl = $url . $query; $xml = simplexml_load_file($reqUrl); $total = (int) $xml['total']; // Need to typecast, or it'll be an object echo $xml->asXML(); // Look at the source code to see what you fetched
The last line (echo $xml->asXML()) isn’t necessary - it’s just to give you an idea of the information you just fetched. It isn’t a whole lot - but we didn’t ask for a whole lot.
The piece of information we wanted was the total number of stories in our topic. That’s the ‘total’ attribute of the ’stories’ element. We fetched it with $xml['total'] and stored it in the $total variable.
Last Step: Fetching the Random Story
With this information in hand, we can craft a new request and get our random story. You can copy and paste the same information we used before, but make these changes to the $params array.
$params['count'] = 1; // We want one story $params['offset'] = rand(0, $total);
By generating a random value for offset between 0 and the maximum, we’re effectively choosing one random story from the available list.
Now run the script again. At the end, $xml should have one random story stored in it. The story information is stored in the story child element, and we can access some of the information like this.
echo $xml->story['link']; // the URL echo $xml->story['submit_date']; // timestamp when it was submitted echo $xml->story->title; echo $xml->story->description;
If you browse through the source code of the xml you outputted, you’ll find all of the essential information about the story. Now you can format it nicely and add it to your website.
In case you ran into trouble along the way, here’s the complete source code of the script. You’ll need to go in and change the topic to your desired topic and set your own appkey, but otherwise it should be all set to go.







Geoserv said this on April 15th, 2008 at 7:08 pm
STUMBLED!
Great tutorial.
Voted for you at:
http://www.newsdots.com/tutorials/how-to-get-a-random-from-digg-with-php-and-xml/