Google chart sparkline – encoding in PHP

The Google Chart API is quite powerful and easy to use, with many customisations available. For my projects i’ve been using the ‘simple encoding‘ method for passing chart data to the Google Chart API. After doing a search on the Internet for a PHP script that converts the data into the encoded string and failing miserably I decided to write my own. This simple PHP function to convert a numerical array of data into the encoded string.

<?php
function simpleEncode($valueArray,$maxValue) {
	$simpleEncoding = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
	$str = 's:';
	$t = count($valueArray);
	for ($i=0;$i<$t;$i++) {
		$currentValue = $valueArray[$i];
		if ((strlen($currentValue)!=0) && ($currentValue>=0)) {
    		$str .= substr($simpleEncoding,round((strlen($simpleEncoding)-1) * $currentValue / $maxValue),1);
    	}
      	else {
      		$str .= '_';
      	}
  	}
	return $str;
}
?>

You can then create the graph in a similar fashion to this:

<?php
$data = array(1,3,5,3,2,9,1,10,4);
?>
<img alt="sparkline" src="http://chart.apis.google.com/chart?cht=lc&chs=100x30&chls=1,1,0&chxt=r,x,y
&chxs=0,990000,11,0,_|1,990000,1,0,_|2,990000,1,0,_&chxl=0:||1:||2:||&chd=<?php echo simpleEncode($data,max($data)); ?>"/>

Which would output something similar to this:

example sparkline

Tags: , , ,


Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>