Skip to content

Instantly share code, notes, and snippets.

@grimmdude
Last active December 26, 2015 08:39
Show Gist options
  • Save grimmdude/7123553 to your computer and use it in GitHub Desktop.
Save grimmdude/7123553 to your computer and use it in GitHub Desktop.
PHP script to pull share counts from Twitter and Facebook for a given url. Takes a csv list of urls to check for and outputs a csv with the urls/share counts.
<?php
/**
* Script to pull share counts from Twitter and Facebook for a given url. Takes a csv list of urls to check for and outputs a csv with the urls/share counts.
* @author Garrett Grimm 2012
* @param $input_csv Path to input csv.
* @param $output_csv Path to output csv.
*/
$input_csv = 'share_urls.csv';
$output_csv = 'share_urls_output.csv';
if (!function_exists('curl_init')) {
die('Curl not installed.');
}
/// Go through csv and perform queries
if ($input_csv_handle = fopen($input_csv, 'r')) {
if ($output_csv_handle = fopen($output_csv, 'w')) {
while ($data = fgetcsv($input_csv_handle)) {
if (filter_var($data[0], FILTER_VALIDATE_URL)) {
$ch_facebook = curl_init();
curl_setopt($ch_facebook, CURLOPT_URL, get_facebook_endpoint($data[0]));
curl_setopt($ch_facebook, CURLOPT_REFERER, "http://google.com");
curl_setopt($ch_facebook, CURLOPT_USERAGENT, "Mozilla/1.0");
curl_setopt($ch_facebook, CURLOPT_RETURNTRANSFER, true);
$facebook_response = json_decode(curl_exec($ch_facebook));
$facebook_count = isset($facebook_response->data[0]->total_count) ? $facebook_response->data[0]->total_count : 0;
curl_close($ch_facebook);
$ch_twitter = curl_init();
curl_setopt($ch_twitter, CURLOPT_URL, get_twitter_endpoint($data[0]));
curl_setopt($ch_twitter, CURLOPT_REFERER, "http://google.com");
curl_setopt($ch_twitter, CURLOPT_USERAGENT, "Mozilla/1.0");
curl_setopt($ch_twitter, CURLOPT_RETURNTRANSFER, true);
$twitter_response = json_decode(curl_exec($ch_twitter));
$twitter_count = isset($twitter_response->count) ? $twitter_response->count : 0;
curl_close($ch_twitter);
/// Write result to output csv
$output_array = array($data[0], $facebook_count, $twitter_count);
fputcsv($output_csv_handle, $output_array);
}
echo "$data[0]...\n";
}
fclose($output_csv_handle);
}
else {
echo 'Cannot open '.$output_csv.' for writing.';
}
fclose($input_csv_handle);
}
else {
echo 'Cannot open '.$input_csv.' for reading.';
}
function get_facebook_endpoint($url) {
return "http://graph.facebook.com/fql?q=SELECT%20url,%20normalized_url,%20share_count,%20like_count,%20comment_count,%20total_count,commentsbox_count,%20comments_fbid,%20click_count%20FROM%20link_stat%20WHERE%20url='".$url."'";
}
function get_twitter_endpoint($url) {
return "http://urls.api.twitter.com/1/urls/count.json?url=".$url;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment