Last active
August 29, 2015 14:22
-
-
Save simonpioli/52d8b942cf38b5429e98 to your computer and use it in GitHub Desktop.
Get the Google Plus One count for a given URL
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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