A PHP class for generating tag clouds

The following PHP code is a simple class that can generate tag cloud in any web pages.

<?php

class TagCloud
{
	private $_counts = array();
	private $_tags = array();
	private $_urls = array();
	private $_levels = array();
	private $__level = 10;

	function __construct()
	{
	}

	function add($tag,$count,$url)
	{
		$this->_counts[$tag] = "$count";
		$this->_tags[$tag] = "$tag";
		$this->_urls[$tag] = "$url";
	}

	function css()
	{
		$css = "#htmltagcloud { text-align:  center; line-height: 1; }\n";
		for ($l=0; $l<$this->__level; $l++)
		{
			$font = 11 + $l;
			$css .= "span.tagcloud$level { font-size: ${font}px;}\n";
			$css .= "span.tagcloud$level a {text-decoration: none;}\n";
		}
		return $css;
	}

	function calclevel()
	{
		//sort($this->_counts);

		$max = log(max($this->_counts));
		$min = log(min($this->_counts));
		$factor = 0;;

		// special case all tags having the same count
		if ($max - $min == 0)
		{
			$min = $min - $this->__level;
			$factor = 1;
		}
		else
		{
			$factor = $this->__level / ($max - $min);
		}

		if (count($this->_counts) < $this->__level )
		{
			$factor *= count($this->_counts)/$this->__level;
		}

		foreach ($this->_counts as $key => $count)
		{
			$this->_levels[$key] = (int)((log($this->_counts[$key]) - $min) * $factor);
		}
	}

	function html()
	{
		$ntags = count($this->_tags);
		if ($ntags <= 0)
		{
			return "<div id='htmltagcloud'>Nothing to do</div>";
		}
		$this->calclevel();
		sort($this->_tags);
		$html = "";
		foreach (($this->_tags) as  $key => $tag)
		{
			$html .=  " <span class=\"tagcloud".$this->_levels[$tag].
					"\"><a href=\"".urldecode($this->_urls[$tag]).
					"\" title=\"".$this->_counts[$tag].
					"\">".$tag."</a></span> ";
		}
		return "<div id='htmltagcloud'>$html</div>";
	}

	function html_and_css()
	{
		$html = "<style type=\"text/css\">" . $this->css() . "</style>";
		$html .= $this->html();
		return $html;
	}

}

?>
  • Share/Bookmark

Leave a Reply

You must be logged in to post a comment.