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.

Bookmark and Share:
  • Digg
  • Furl
  • del.icio.us
  • StumbleUpon
  • MisterWong
  • DZone
  • Technorati

Tags: , , ,

8 Comments to “Digg API: Grabbing a Random Digg Story with PHP”

  1. Geoserv said this on

    STUMBLED!

    Great tutorial.

    Voted for you at:
    http://www.newsdots.com/tutorials/how-to-get-a-random-from-digg-with-php-and-xml/

  2. Digg API: Showing latest stories from your site/URL/domain « Wuwei2k2 Blog said this on

    [...] PHP code will display the latest 20 stories from the domain of your choice. Thanks a heap to Web Cash’s entry on grabbing a random Digg story as well as the Digg Story API which helped with this [...]

  3. Aaron said this on

    This is sweet! Thanks for taking the time to share.
    I’m using it for a random auto related story.
    I did add a target=_blank so visitors wouldn’t leave our page however.

  4. hhhh said this on

    this is wonderful tutorial .. i read it 3 times and get a fantastic results and sure i put a
    copy of this lesson on my site here
    السهول
    قبيلة السهول

    http://www.suhol.com/vb

  5. Increase Traffic said this on

    I have a few sites I go to, but the quality is always the best here!

  6. Digg API: How to Get a Random Story from Digg - Tutorial Collection said this on

    [...] View Tutorial No Comment var addthis_pub=”izwan00″; BOOKMARK This entry was posted on Friday, June 5th, 2009 at 8:11 am and is filed under Php Tutorials. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site. [...]

  7. php tutorials said this on

    Great tutorial , thank you !

  8. Sid Barrientes said this on

    Many thanks for sharing such an insightful article with all of us. I’ve bookmarked your blog will come back for a re-read again. Keep up the very good work. We have a Dan Kennedy Copywriting seminar that we offer to our customers you can check it out here Copywriting Tips Click here

Leave a Reply