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

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

Google [see below for JSON-RPC]


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("" + 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("" + url);

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

	return count;

int GetPlusOnes(string url) {

	string googleApiUrl = ""; //?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);

	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();


	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;


Again, thanks to Tom Anthony for the Google part

function get_tweets($url) {

	$json_string = file_get_contents('' . $url);
	$json = json_decode($json_string, true);

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

function get_likes($url) {

	$json_string = file_get_contents('' . $url);
	$json = json_decode($json_string, true);

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

function get_plusones($url) {

	$curl = curl_init();
	curl_setopt($curl, CURLOPT_URL, "");
	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!

81 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"}]’ % ""
    url = ""
    req = urllib2.Request(url, data, {‘Content-Type’: ‘application/json’})
    f = urllib2.urlopen(req)
    response =

    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(‘’ . $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:


    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.


  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 It’s a fast and easy Like Exchange system, and I’ve already gotten more than a thousand Likes. Check it out!. My favorite site to get Plus Ones for Google+ is

  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?


  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. Thank You Devil 😉

  20. Sunny says:

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

    check this

  21. Beko says:

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

    1200k etc
    2100k etc… and

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

  23. JoeyJ says:

    You can get your web site share count data from Is free service!!

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

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

  26. 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,,

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

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

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

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

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

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

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

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

  35. Hassan says:

    how it will show result

  36. 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? 😛 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

  37. Budy K says:

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

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

  39. 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…

  40. says:

    Any code available in Jquery or JavaScript for this problem?

  41. free movies says:

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

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

  42. 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!

  43. 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!

  44. Elbert says:

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

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

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

  47. honda jazz says:

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

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

  49. Per Kristian says:

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

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

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

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

  53. laurence says:

    Try this awesome tools which give you real time facebook like and share for several URL in the same time.

  54. 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!

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

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

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

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

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

  60. 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!

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

  62. cat pictures says:

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

  63. 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!

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

  65. 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?

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

  67. 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?
    😛 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?

  68. Paki says:

    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.

  69. 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!

  70. 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!

  71. Spot on with this write-up, I actually believe this site needs a lot more attention.
    I’ll probably be back again to read more, thanks for the advice!

  72. Thank you for any other informative blog. The place
    else may I get that kind of info written in such
    an ideal approach? I have a undertaking that I’m just now operating on, and
    I have been on the glance out for such info.

  73. 、それは私のためか月となっています。私はあまりにも長い間待っていたされていますさて、この記事。私は大学で私の割り当てを完了するために書き込むのこの部分を必要とし、それはあなたの記事と同じトピックを持っています。おかげで、大きなシェア。

  74. dasdasd says:

    Excellent web site you have got here.. It’s difficult to find good quality writing like yours these days.
    I truly appreciate individuals like you!
    Take care!!

  75. 420 says:

    I Ƅelieve that іss one of thᥱ sucϲҺ а ⅼоt іmроrtant іnfогmɑtіоn fоr me.
    Аnd і’m gⅼaԁ stսԀʏіng үοur artісⅼе.
    Ηοաеvеr ѕҺսlԁ геmaгк оn fеԝ Ƅaѕіс
    thіngѕ, Theе ѕοtе ѕtylе іѕ idᥱɑⅼ,
    tҺe aгtісlеѕ іѕ
    ɑϲtᥙаⅼⅼʏ ᥱxcеlⅼгnt : Ⅾ.

    Јᥙѕt гiǥɦt ргоϲеѕs,

    Herᥱ iѕѕ mу ѡᥱЬѕіtе …


  76. Florencia says:

    Excellent, what a webpage it is! This webpage gives helpful information to us, keep it up.

  77. carriel says:

    Javala Outdoor adalah anak jenis usaha dari Djavala Group ( yang sudah berkembang dari tahun 2014.
    Djavala memiliki lebih dari 3 jenis usaha seperti penyedia
    / supplier barang-barang outdoor (,
    penyedia service layanan untuk perjalanan wisata tour & travel baik international dan domestik khusus Indonesia (,
    penyedia barang-barang distro / style ( hingga merancah kedunia bisnis kuliner / makanan
    / snack.
    Bisnis usaha menjual barang outdoor dan penyewaan / sewa barang outdoor keril,carriel,carrier,daypack,
    sepatu gunung,boots,cover bag,tenda,kompor,headlamp,outdoor,javalaoutdoor,javala,djavala,treking pole,jaket polar,
    jaket gunung,dryback,peralatan gunung,peralatan climbing.

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