Getting Number of Pinterest Pins in PHP

Since pinterest has repeatedly given a date and then subsequently failed to release their API, I decided to take the matter into my own hands. Please note that this is not the ideal way to do things, but, for now it works. I wanted to build a social graph of our most popular pages so we could know what kind of photos and content was resonating with our viewers, so I came up with the script below and then looped through every URL in our database and got the data I needed.

I drilled down into the iframe that was created by a pinterest button callout and came up with this url:
Well that was easy, the number is displayed right there in its own div id CountBubble. So I curl’ed it, and used the simple_html_dom php library to parse. It kept returning 0 though. Whoops! That number is changed with javascript after the page is loaded. Should have viewed the source instead of inspecting the element. So I view the source instead and there’s this nice piece of code just sitting there for my programming pleasure.

snode.setAttribute('src', '//'+targetUrl);

From that, I gather the following URL will probably pull the data I need,
which displays:

receiveCount({"count": 1148, "url": ""})

So, its json data wrapped in a function call from the API they haven’t released publicly yet. How convenient. Below is the little bit of code you need to make this work in PHP. You must have cURL enabled on your server.

$pinurl = "";

$targeturl = "";
$pinurl .= $brandurl;
$html = pull_html($pinurl);       //get the html through a function that calls cURL

$html = str_replace("receiveCount(","",$html);    //remove the function call the data is wrapped in
$html = substr($html,"", -1);
$pinterest = json_decode($html);        //convert from json to php array
$pincount = $pinterest->count;

echo $pincount;   //  there's the number

function pull_html($url)
$ch = curl_init();
$html = curl_exec($ch);

return $html;

As you can see, we pull the data with curl then strip out the function call that’s wrapped around the json data. Then it’s just a matter of using json_decode to turn the json data into a php array. Voila! All done. I have run around 3,000 URLs so far and the data has returned no problem. It was a little slow at times, not sure if by design or by . Its still pulling and storing the data as I type this. I’m sure at some point there will be some sort of rate limiting, but I haven’t run into any walls so far. Maybe this isn’t even supposed to be hidden from programmers, but as far as I know, there is no official support unless you’re one of the few publishers they have chosen to work with.

Posted by Will on June 7, 2012

Leave a Reply

Your email address will not be published. Required fields are marked *

TechJunkie Also Recommends