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

June 7, 2011 | .NET, JavaScript, PHP | 74 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!

74 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.

  44. house says:

    Admiring the commitment you put into your site and detailed
    information you offer. It’s good to come across a blog every once in a while that isn’t
    the same unwanted rehashed material. Fantastic read! I’ve
    bookmarked your site and I’m adding your RSS feeds
    to my Google account.

  45. I think that what you posted was very reasonable. However, think on this, what
    if you were to write a awesome post title? I am not suggesting
    your content isn’t good., but suppose you added a headline to maybe get folk’s attention?
    I mean Getting Counts for Twitter Links, Facebook
    Likes/Shares, and Google (+1) PlusOnes in C# or PHP | John Dyer’s Code is kinda plain.

    You might peek at Yahoo’s front page and watch how they create post headlines to get
    viewers to click. You might try adding a video or a pic or two to get
    readers excited about everything’ve written. Just my opinion,
    it might make your posts a little livelier.

  46. honda jazz says:

    Awesome! Its actually amazing paragraph, I have got much clear idea concerning from this article.

  47. Thank you a bunch for sharing this with all people you actually recognise what you are speaking approximately!
    Bookmarked. Please additionally consult with my web site =).
    We may have a link alternate arrangement between us

  48. Per Kristian says:

    Here’s a related Javascript class which lets you get the same information from Facebook, Twitter and LinkedIn.

    https://404it.no/en/blog/javascript_class_for_getting_url_shares_on_facebook_twitter_linkedin

  49. I always spent my half an hour to read this blog’s content every
    day along with a mug of coffee.

  50. of course like your web site but you need to test the spelling on quite
    a few of your posts. A number of them are rife with spelling
    problems and I to find it very troublesome to inform the reality nevertheless I will surely come again again.

  51. Thanks for the code snippets. I have used the PHP code version for various of my projects and it is working perfectly well.

  52. laurence says:

    Try this awesome tools http://www.facebooklikecount.com/ which give you real time facebook like and share for several URL in the same time.

  53. Spot on with this write-up, I seriously feel this amazing site needs much more attention.
    I’ll probably be returning to read through more, thanks for the information!

  54. gag says:

    I’m amazed, I have to admit. Seldom do I come across a blog that’s equally educative and amusing, and let me tell you, you’ve hit the nail on
    the head. The problem is an issue that not
    enough men and women are speaking intelligently about. I am very happy I found
    this in my search for something regarding this.

  55. manga says:

    Thanks for any other excellent post. The place else may just anyone get that kind of information in such an ideal manner
    of writing? I’ve a presentation next week, and I am on the search
    for such information.

  56. Hi there, everything is going well here and ofcourse every one is
    sharing information, that’s genuinely excellent, keep up writing.

  57. Big Tits says:

    I do believe all the ideas you’ve presented in your post.
    They are really convincing and can definitely work. Still, the
    posts are too brief for beginners. May just you please extend
    them a bit from next time? Thanks for the post.

  58. I’ve learn a few just right stuff here. Certainly worth bookmarking for
    revisiting. I wonder how a lot attempt you place to create any such excellent informative web
    site.

  59. My brother suggested I may like this website. He was entirely right.

    This post actually made my day. You can not consider simply how much time
    I had spent for this info! Thank you!

  60. Hi, the whole thing is going nicely here and ofcourse every one is
    sharing data, that’s in fact fine, keep up writing.

  61. cat pictures says:

    Hi there mates, its enormous article regarding teachingand fully defined,
    keep it up all the time.

  62. You should be a part of a contest for one of the best websites on the internet.
    I most certainly will highly recommend this blog!

  63. I’m very pleased to find this website. I need to to thank you
    for ones time for this fantastic read!! I definitely liked every part of it and i also have you bookmarked to look at new things on your
    website.

  64. Amazing things here. I’m very satisfied to see your post.
    Thanks so much and I am taking a look forward to contact you.
    Will you kindly drop me a mail?

  65. Very quickly this site will be famous among all blog
    users, due to it’s good content

  66. I seldom comment, however i did some searching and wound up here Getting Counts for Twitter Links,
    Facebook Likes/Shares, and Google (+1) PlusOnes in C# or PHP | John Dyer’s Code.

    And I do have a few questions for you if it’s allright.
    Is it just me or does it appear like a few of these responses look like they are left by brain dead people?
    :-P And, if you are posting at other online social
    sites, I would like to keep up with everything new
    you have to post. Could you make a list
    of all of all your shared pages like your linkedin profile, Facebook page
    or twitter feed?

  67. Paki says:

    Hi,
    Any one can help me please….!!
    i need a code for

    Get details of users/visitors who share our URL on Facebook, Twitter.

    i need a list of peoples who share our link on facebook and twitter.

  68. Pretty nice post. I simply stumbled upon your weblog and wanted to mention
    that I’ve truly enjoyed surfing around your blog posts.
    In any case I’ll be subscribing on your feed and
    I’m hoping you write once more soon!

  69. Right here is the right blog for anyone who wants to understand this topic.

    You know a whole lot its almost hard to argue with you (not that I really would want to…HaHa).

    You definitely put a new spin on a subject that has been discussed for ages.

    Wonderful stuff, just great!

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.