on Tutorials

How to get number of Uri.lv feed subscribers with PHP

0 comments
Codeforest
Tweet about this on TwitterShare on FacebookShare on Google+Share on LinkedInShare on RedditShare on StumbleUpon

Few days ago I wrote a tutorial on how to migrate your feed from Google’s Feedburner to Uri.lv and I promised I will write a follow up on how to get number of subscribers.

Uri.lv has a neat URL to JSON file with your data and this is what we’ll use today. It can be found inside Uri.lv admin interface under Miscellaneous.

This file contains number of subscribers as well as some statistics data for the last seven days.

Get number of subscribers

Let’s get our hands dirty. First, we will make this in conventional PHP, so anybody can use it. First, let’s see how that JSON file looks like:

{
    "subscribers": 534,
    "hits": 13665,
    "graph": {
        "title": "URI.LV Subscribers for \/codeforest",
        "type": "line",
        "datasequences": [
            {
                "title": "Feed",
                "color": "red",
                "datapoints": [
                    {
                        "title": "2013-05-14",
                        "value": 666
                    },
                    {
                        "title": "2013-05-15",
                        "value": 668
                    },
                    {
                        "title": "2013-05-16",
                        "value": 654
                    },
                    {
                        "title": "2013-05-17",
                        "value": 668
                    },
                    {
                        "title": "2013-05-18",
                        "value": 665
                    },
                    {
                        "title": "2013-05-19",
                        "value": 630
                    },
                    {
                        "title": "2013-05-20",
                        "value": 630
                    }
                ]
            }
        ]
    }

There is something strange when you look at the data, I have 534 subscribers and inside the graph part, there are bigger numbers. 534 represents the number of people who accessed the feed through some kind of a reader, while inside graph part all hits are counted (both readers and direct).
Ok, let write some simple PHP code to harvest this, I will use the cURL as it is the standard:

$url = 'YOUR_URI.LV_URL'; // replace this with your own

// plain non cached method
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 1);
$results = curl_exec($ch);
curl_close($ch);

$results = json_decode($results);

if (!empty($results)) {
	$subscriberNumber = $results->subscribers;
	echo 'You have ' . $subscriberNumber . ' subscribers!';
} else {
	echo 'Something is wrong!';
}

Pretty simple. But, every time you refresh your page, this code is getting the file from the server and that’s not to optimized.
So let’s add some simple file caching to the story:

$url = 'YOUR_URI.LV_URL'; // replace this with your own

// Caching the result in a file
$fileName = 'cache.tmp';
$cacheTime = 60 * 5; // 5 minutes
// we have a cache less than 5 minutes old
if (file_exists($fileName) && time() - $cacheTime < filemtime($fileName)) {
    $handle = fopen($fileName, 'rb');
    $subscriberNumber = fread($handle, filesize($fileName));
    fclose($handle);
} else { // cache file does not exist or is expired, so let's get the result and cache it
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_TIMEOUT, 1);
	$results = curl_exec($ch);
	curl_close($ch);

	$results = json_decode($results);

	if (!empty($results)) {
		$subscriberNumber = $results->subscribers;
		$handle = fopen($fileName, 'w+'); // we want to overwrite the value!
		fwrite($handle, $subscriberNumber);
		fclose($handle);
	}
}

echo 'You have ' . $subscriberNumber . ' subscribers!';

Nice. Now we are caching the number for 5 minutes and the code is optimized.

WordPress version

For those guys like me that use WordPress, it’s even simpler, just add this code to your theme’s functions.php file:

// WordPress version, this function goes to your functions.php theme file
/**
 * get RSS readers count
 * @param string uri.lv json url
 * @return int
 */
function getRssCount($url)
{
	$transientKey = "uri_lv_subscribers";

    $rssCount = get_transient($transientKey);

    if (false === $rssCount) {

		$remote = wp_remote_get($url);

		// If the API data request results in an error, return
		// some number 🙂
		if (is_wp_error($remote)) {
			return '601';
		}
		$data = json_decode( $remote['body'] );
		$rssCount = $data->subscribers;
		set_transient('uri_lv_subscribers', $rssCount, 60*60*12);
    }

	return $rssCount;
}

This code is using fantastic WordPress transient API to cache the number of subscribers.

Now, add this code wherever you want to show your number of subscribers:

// put something like this where you want to show subscribers count:
echo 'Subscribers: ' . getRssCount('YOUR_URI.LV_URL'); // change URL to yours

Subscribers statistics chart

As you saw above, JSON has some handy statistics data, so let’s play with it a bit. We’re going to use the Google Charts API to draw a line chart with our statistics.

Here is the code:

<html>
  <head>
   	<title>Codeforest URI.LV subscribers chart demo</title>
  </head>
  <body>

    <div id="chart_div" style="width: 900px; height: 500px;"></div>

    <?php
		$url = 'YOUR_URI.LV_URL';

		// Caching the result in a file
		$fileName = 'cache.tmp';
		$cacheTime = 60 * 10; // 10 minutes
                // we have a cache less than 5 minutes old
		if (file_exists($fileName) && time() - $cacheTime < filemtime($fileName)) {
		    $handle = fopen($fileName, 'rb');
		    $results = unserialize(fread($handle, filesize($fileName)));
		    fclose($handle);
		} else { // cache file does not exist or is expired
			$ch = curl_init();
			curl_setopt($ch, CURLOPT_URL, $url);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			curl_setopt($ch, CURLOPT_TIMEOUT, 1);
			$results = curl_exec($ch);
			curl_close($ch);

			$results = json_decode($results);

			if (!empty($results)) {
				$result = serialize($results);
				$handle = fopen($fileName, 'w+'); // we want to overwrite the value!
				fwrite($handle, $result);
				fclose($handle);
			}
		}

		if (!empty($results)) {
			$title = $results->graph->title;
			// let's generate data for the chart
			$data = "['Date', 'Subscribers'],";
			foreach ($results->graph->datasequences[0]->datapoints as $datapoint) {
				$data .= "['" . $datapoint->title . "', " . $datapoint->value . "],";
			}
		} else {
			die('Something is wrong! No data received...');
		}
	?>
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript">
      google.load("visualization", "1", {packages:["corechart"]});
      google.setOnLoadCallback(drawChart);
      function drawChart() {
        var data = google.visualization.arrayToDataTable([
          <?php echo $data; ?>
        ]);

        var options = {
          title: '<?php echo $title; ?>',
          curveType: 'function',
          legend: {position: 'bottom'}
        };

        var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
        chart.draw(data, options);
      }
    </script>
  </body>
</html>

This code will draw a nice chart with our subscribers statistics.

That concludes our tutorial. There is a demo of the chart available below:

Demo

What’s next

Well, in a week or two I plan to write a WordPress plugin tutorial which will have a widget for showing the subscriber number and admin statistics charts. So, stay tuned.

Tweet about this on TwitterShare on FacebookShare on Google+Share on LinkedInShare on RedditShare on StumbleUpon



Comments are closed.