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

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

57 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. Sunny says:

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

    check this

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

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

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

  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!

  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

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

  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 which give you real time facebook like and share for several URL in the same time.

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