Getting Counts for Twitter Links, Facebook Likes/Shares, and Google (+1) PlusOnes in C# or PHP

June 7, 2011 | .NET, JavaScript, PHP | 48 Comments

I am working on a project where I need to know the number of social shares on Facebook, Twitter, and Google +1 (plusone). Facebook and Twitter make this easy with a simple URL that returns clear JSON data, but Google has not offered an official way to do it yet. However, I found someone who tracked down how to do it using Google’s JSON-RPC API, and I’ve repackaged them together in ASP.NET and PHP for anyone who wants to give it a try.

Data URLs

Here’s where you can find the data

Facebook http://graph.facebook.com/?ids=YOURURL
Twitter http://urls.api.twitter.com/1/urls/count.json?url=YOURURL
Google https://clients6.google.com/rpc [see below for JSON-RPC]

ASP.NET C#

Note: Since I’m using “dynamic,” this requires .NET 4.0. Also, I’m using the JavaScriptSerializer class which is officially depreciated, but will probably not actually be removed. You could also easily use Regex to get these simple values.

int GetTweets(string url) {

	string jsonString = new System.Net.WebClient().DownloadString("http://urls.api.twitter.com/1/urls/count.json?url=" + url);

	var json = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize(jsonString);
	int count = (int)json["count"];	

	return count;
}

int GetLikes(string url) {

	string jsonString = new System.Net.WebClient().DownloadString("http://graph.facebook.com/?ids=" + url);

	var json = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize(jsonString);
	int count = json[url]["shares"];

	return count;
}

int GetPlusOnes(string url) {

	string googleApiUrl = "https://clients6.google.com/rpc"; //?key=AIzaSyCKSbrvQasunBoV16zDH9R33D88CeLr9gQ";

	string postData = @"[{""method"":""pos.plusones.get"",""id"":""p"",""params"":{""nolog"":true,""id"":""" + url + @""",""source"":""widget"",""userId"":""@viewer"",""groupId"":""@self""},""jsonrpc"":""2.0"",""key"":""p"",""apiVersion"":""v1""}]";

	System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(googleApiUrl);
	request.Method = "POST";
	request.ContentType = "application/json-rpc";
	request.ContentLength = postData.Length;

	System.IO.Stream writeStream = request.GetRequestStream();
	UTF8Encoding encoding = new UTF8Encoding();
	byte[] bytes = encoding.GetBytes(postData);
	writeStream.Write(bytes, 0, bytes.Length);
	writeStream.Close();

	System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();
	System.IO.Stream responseStream = response.GetResponseStream();
	System.IO.StreamReader readStream = new System.IO.StreamReader(responseStream, Encoding.UTF8);
	string jsonString = readStream.ReadToEnd();

	readStream.Close();
	responseStream.Close();
	response.Close();

	var json = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize(jsonString);
	int count = Int32.Parse(json[0]["result"]["metadata"]["globalCounts"]["count"].ToString().Replace(".0", ""));

	return count;
}

PHP

Again, thanks to Tom Anthony for the Google part

function get_tweets($url) {

	$json_string = file_get_contents('http://urls.api.twitter.com/1/urls/count.json?url=' . $url);
	$json = json_decode($json_string, true);

	return intval( $json['count'] );
}

function get_likes($url) {

	$json_string = file_get_contents('http://graph.facebook.com/?ids=' . $url);
	$json = json_decode($json_string, true);

	return intval( $json[$url]['shares'] );
}

function get_plusones($url) {

	$curl = curl_init();
	curl_setopt($curl, CURLOPT_URL, "https://clients6.google.com/rpc");
	curl_setopt($curl, CURLOPT_POST, 1);
	curl_setopt($curl, CURLOPT_POSTFIELDS, '[{"method":"pos.plusones.get","id":"p","params":{"nolog":true,"id":"' . $url . '","source":"widget","userId":"@viewer","groupId":"@self"},"jsonrpc":"2.0","key":"p","apiVersion":"v1"}]');
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-type: application/json'));
	$curl_results = curl_exec ($curl);
	curl_close ($curl);

	$json = json_decode($curl_results, true);

	return intval( $json[0]['result']['metadata']['globalCounts']['count'] );
}

Hope that helps someone out there!

48 Responses to “Getting Counts for Twitter Links, Facebook Likes/Shares, and Google (+1) PlusOnes in C# or PHP”

  1. Seth says:

    just for fun I cobbled together a python example

    import urllib2, json

    data = ‘[{"method":"pos.plusones.get","id":"p","params":{"nolog":true,"id":"%s","source":"widget","userId":"@viewer","groupId":"@self"},"jsonrpc":"2.0","key":"p","apiVersion":"v1"}]’ % "http://www.tomanthony.co.uk/"
    url = "https://clients6.google.com/rpc?key=AIzaSyCKSbrvQasunBoV16zDH9R33D88CeLr9gQ"
    req = urllib2.Request(url, data, {‘Content-Type': ‘application/json’})
    f = urllib2.urlopen(req)
    response = f.read()
    f.close()

    result = json.loads(response)

    print int(result[0][‘result’][‘metadata’][‘globalCounts’][‘count’])

  2. Nick says:

    Helps me. I was looking for that. i get an error but i think its a firefox error but ill throw it out there just in case.

    permission denied from to get property Proxy.InstallTrigger.

    if you get any idea what that is.

  3. Dragomir says:

    If you want to get Facebook `total_count` (e.g. `likes` + `shares`) here is a modification of the function:

    function get_likes($url) {

    $json_string = file_get_contents(‘http://graph.facebook.com/?ids=’ . $url);
    $json = json_decode($json_string, true);

    $total_count = 0;

    if (isset($json[$url][‘shares’])) $total_count += intval($json[$url][‘shares’]);
    if (isset($json[$url][‘likes’])) $total_count += intval($json[$url][‘likes’]);

    return $total_count;
    }

  4. andy killen says:

    Thanks John, just what I needed. the google+ details were illusive elsewhere. And thanks for Tom also for doing the php version.

  5. Alex says:

    Hi,

    Can anyone explain how to use the PHP code to display the number of likes on a html page?
    I would like to know how to use it.

    cheers
    Alex

  6. Josie Martin says:

    I reply on marketing on Facebook and Google Plus a lot. My favorite site to get Likes for my Facebook page is GetLikesEasy.com. It’s a fast and easy Like Exchange system, and I’ve already gotten more than a thousand Likes. Check it out!. http://GetLikesEasy.com. My favorite site to get Plus Ones for Google+ is GetPlusOnesGoogle.com. http://GetPlusOnesGoogle.com

  7. analyzer says:

    Thanks for sharing. I could run facebook and twitter but google code gives “Invalid Data” error?

  8. seo says:

    Google+ doesn’t work. I think its not related with Google console settings.

  9. Thanks John, just what I needed. the google+ details were illusive elsewhere.

  10. Anees says:

    Thank you :) Use full one
    And now +1 is not working always zero

  11. ahmadalli says:

    this isn’t correct: var json = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize(jsonString); from googleplus method of c#. because Deserialize wanted two Arguments

    • Sam says:

      Hey were you guys to figure out how to parst the json response like you said
      var json = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize(jsonString);
      int count = json[url][“shares”];

      This doesn’t see to be working.

  12. […] a method to get a webpage url and return count of it’s +1. I searched google and just find this and the method […]

  13. Neo says:

    Thanks! Now my G+ works..

  14. e-devlet says:

    Thanks, I couldn’t run Google+ too with Asp.Net.
    Neo how could you run it, can you share it pls.

  15. devil says:

    Well as for Google Plus
    same url
    on a Google Pages of My web site i get 5 likes !
    But with this code i get 2 shares?

    How can i get a page pluses – likes

  16. Bibhuti says:

    Thanks, very useful post. Do you have php code to get “pin it” count?

    Thanks,
    Bibhuti

  17. Ada Ali says:

    Like count is different with share count in Facebook. Your code is for share count. How to get just for Facebook like count?
    Nice code by the way!

  18. […] Special thanks to Eric Matthys for his base inline loading widget and to John Dyer for his post on retrieving counts from various Social Networks. […]

  19. Sunny says:

    i have add four more functions to get Linkedin share, delicious bookmarks, Pinterest share, stumbleupon view

    check this http://toolspot.org/script-to-get-shared-count.php

  20. Beko says:

    I have a php code for the counter but I need to add something to the counter is as follows:

    1k
    1100k
    1200k etc
    2k
    2100k etc… and
    2m
    2500m

  21. Thanks for sharing. I could run facebook and twitter but google code gives “Invalid Data” error? its help me :)

  22. JoeyJ says:

    You can get your web site share count data from http://pgurl.com. Is free service!!

  23. md shohagh says:

    hi i want use the same thing what u use here ,facebook like button then in small box count of like.please let me know the code or tell me where i get that code,

    Thank you

  24. I do agree with all the ideas you’ve offered to your post.
    They’re very convincing and can certainly work. Nonetheless,
    the posts are too quick for newbies. Could you please lengthen
    them a bit from next time? Thanks for the
    post.

  25. Buy Genuine Facebook fans operates exclusively with true human beings that will interact with your material, your comments and ultimately with your solution. These are not dummy
    accounts! Not only we can deliver you thousands of targeted,real people today who are interested in your enterprise,solutions or services,but
    also we can assure you accomplishment as properly as we provide
    the highest-high quality fans packages out there on the
    net nowadays.Pay a visit to our packages for beginning your Facebook
    campaign. facebook likes status, https://pmm.zendesk.com/entries/54669734-10-Facebook-Advertising-Tips-To-Sell-Your-Book,

  26. A recurve gives more arrow energy to a shorter bow than a simple bow, due to which it is often preferred by archers in environment where long weapons are inconvenient. Recurve bows have limbs made of layers of carbon fiber, fiberglass and laminated wood cores.

  27. On lack of in the coffeehouse is bookstore, where students
    be willing to stay at home line to buy cramming books on chemistry, civil service, and English literature alongside parents willing to be out
    within the rain because they buy the latest fashion in notebooks and colored pens for their primary school children. The gems from where rays don’t
    fall include the graces in which souls forget to ask.
    All you must do to start playing a video or audio file is usually to open the downloaded torrent (the torrents
    can be typically just one or two kilobytes in size, so they download instantly.

  28. You could certainly see your enthusiasm within
    the work you write. The sector hopes for more passionate writers like you who aren’t afraid to mention how
    they believe. Always go after your heart.

  29. emelőgép, daru, földmunkagép, üzembehelyezés, emelőgép
    szakértő országosan, profin, megbízhatóan, szakértelemmel.
    Crane and heavy machine expert.

  30. peniaze says:

    I have read so many articles or reviews about
    the blogger lovers except this article is really a fastidious article, keep it up.

  31. webcamgay says:

    It’s very straightforward to find out any topic on net as compared to books, as I found this article at
    this web site.

  32. It’s hard to find knowledgeable people on this subject, however, you sound like you know what you’re talking about!
    Thanks

  33. I know this website presents quality based posts and additional information, is there
    any other site which gives such data in quality?

  34. Hassan says:

    how it will show result

  35. Myles Munroe says:

    I usually do not drop a leave a response, however I read a lot of remarks on Getting Counts for Twitter Links, Facebook Likes/Shares, and Google
    (+1) PlusOnes in C# or PHP | John Dyer’s Code. I actually do have a couple of
    questions for you if it’s okay. Is it only me or do some of the responses look like
    they are coming from brain dead folks? :-P And, if you are writing
    on other social sites, I’d like to keep up with everything fresh you have
    to post. Would you list of every one of all your social community
    sites like your linkedin profile, Facebook page or twitter
    feed?

  36. Budy K says:

    this is what im looking for….gonna try it with PHP and JQuery

  37. Usually I don’t learn article on blogs, but I would like
    to say that this write-up very pressured me to check out and do it!

    Your writing style has been surprised me.
    Thanks, quite great post.

  38. Vikram Raju says:

    By using above code, we will get the life time share counts for specified URL.

    Is there any way to get the share count for particular date range. (like past week, past month)

    Thanks in advance…

  39. ilmiweb.com says:

    Any code available in Jquery or JavaScript for this problem?

  40. free movies says:

    This site was… how do you say it? Relevant!!

    Finally I’ve found something which helped me. Many thanks!

  41. You ought to take part in a contest for one of the most useful
    sites on the net. I most certainly will highly recommend
    this web site!

  42. fantastic publish, very informative. I ponder why the other specialists of
    this sector don’t understand this. You should continue your writing.
    I am sure, you have a huge readers’ base already!

  43. Elbert says:

    What’s up colleagues, pleasant article and nice urging commented here, I am genuinely enjoying by these.

Leave a Reply

Hi, I'm John Dyer. In my day job, I build websites and create online seminary software for a seminary in Dallas. I also like to release open source tools including a pretty popular HTML5 video player and build tools that help people find best bible commentaries and do bible study. And just for fun, I also wrote a book on the theology of technology and media.

Fork me on GitHub

Social Widgets powered by AB-WebLog.com.