Obtaining a Digg count independently
Nevertheless, Digg has been very good in providing a very simple but useful API that allows us to in theory extract any Digg information that you find on their site for your own purposes. While not a web service in the traditional sense of the word, it is still easy to use with PHP.
For the purposes of our counter, all we need to do is retrieve the "diggs" of a certain item – part of the information retrieve from the ["List Stories" endpoint](http://apidoc.digg.com/ListStories ""List Stories" endpoint"). The best identifier we have is the URL of that item, and so we can use the "link" argument as described on the page.
So, we have our information. Now, how do we integrate it into PHP?
If you go to that address, you will see the results in XML format. However, since we are using PHP this is not the most optimal method of obtaining the information. In the end, I just chose to use JSON and Regex the diggs out, instead of crawling through the unserialized PHP object.
First, however, we need to GET that information into our script. Unfortunately, we can’t use
file_get_contents() because that returns a 403 forbidden error. I’m sure Digg have their reasons… but that means we have to use another method. cURL is probably the easiest, but you will have to install it (or ask your host to). Once we have it, we just need to set the proper parameters and call the Digg service.
$url = "http://services.digg.com/stories?type=json&link="; $url .= urlencode("http://stamen.com/clients/cabspotting"); //The item's URL $url .= "&appkey=http%3A%2F%2Fexample.com%2Fapplication"; $curl = curl_init(); //Initialize the cURL session curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 20); //Don't want to wait forever! curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); //Return the page curl_setopt($curl, CURLOPT_URL, $url); //Set the URL $data = curl_exec($curl); //GET it curl_close($curl); //Free up resources
Now, we just extract the Diggs using a regular expression, and you have your number!
preg_match("/\"diggs\":([0-9]+)\,/", $data, $diggs); $diggs = empty($diggs) ? 0 : $diggs;
As a footnote, if we want to find the amount of Diggs for multiple URLs in the same script, it saves resources to just use one cURL session, simply changing the
CURLOPT_URL each time and re-executing.