Skip to content

Instantly share code, notes, and snippets.

@simonpioli
Last active August 29, 2015 14:22
Show Gist options
  • Save simonpioli/52d8b942cf38b5429e98 to your computer and use it in GitHub Desktop.
Save simonpioli/52d8b942cf38b5429e98 to your computer and use it in GitHub Desktop.
Get the Google Plus One count for a given URL
<?php
function getCount($url)
{
//Assumes Guzzle. As long as you make a request to the URL below and grab the body, it doesn't matter how you cURL.
$request = $this->getHttpClient()->get('https://plusone.google.com/_/+1/fastbutton?url='.urlencode($url));
$html = $request->send()->getBody();
// Disable libxml errors
libxml_use_internal_errors(true);
$document = new \DOMDocument();
$document->loadHTML($html);
$aggregateCount = $document->getElementById('aggregateCount');
// Restore libxml errors
libxml_use_internal_errors();
// Instead of big numbers, Google returns strings like >10K or 1.3K, I want a floating point number
if (preg_match('/>*([0-9]+[.]*[0-9]+)([kKmM])/', $aggregateCount->nodeValue, $matches)) {
$count = $matches[1] * 1000;
if (in_array($matches[2], ['m', 'M']) {
$count = $matches[1] * 1000000;
}
} else {
$count = intval($aggregateCount->nodeValue);
}
$this->getCache()->save($site->getId().'_'.$url.'_gpluscount', $count, 1800);
return $count;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment