Wednesday, April 13, 2011

How to Make Tag Cloud with PHP, MySQL and CSS


<?php
mysql_connect('localhost', 'root', '') or die(mysql_error());
mysql_select_db('test');

function tag_info() {
  $result = mysql_query("SELECT * FROM tp_urls GROUP BY title ORDER BY id DESC");
  while($row = mysql_fetch_array($result)) {
    $arr[$row['title']] = $row['id'];
  }
  ksort($arr);
  return $arr;
}

function tag_cloud() {

    $min_size = 10;
    $max_size = 30;

    $tags = tag_info();

    $minimum_count = min(array_values($tags));
    $maximum_count = max(array_values($tags));
    $spread = $maximum_count - $minimum_count;

    if($spread == 0) {
        $spread = 1;
    }

    $cloud_html = '';
    $cloud_tags = array(); // create an array to hold tag code
    foreach ($tags as $tag => $count) {
        $size = $min_size + ($count - $minimum_count)
            * ($max_size - $min_size) / $spread;
        $cloud_tags[] = '<a style="font-size: '. floor($size) . 'px'
            . '" class="tag_cloud" target="_blank" href="http://www.v-nessa.net/index.php?s=' . $tag
            . '" title="\'' . $tag  . '\' returned a count of ' . $count . '">'
            . htmlspecialchars(stripslashes($tag)) . '</a>';
    }
    $cloud_html = join("\n", $cloud_tags) . "\n";
    return $cloud_html;

}

?>

<style type="text/css">
.tag_cloud
{padding: 3px; text-decoration: none;
font-family: verdana; }
.tag_cloud:link  { color: #FF66CC; }
.tag_cloud:visited { color: #9900FF; }
.tag_cloud:hover { color: #FF66CC; background: #000000; }
.tag_cloud:active { color: #6699FF; background: #000000; }
</style>

<div id="wrapper">
 <?php print tag_cloud(); ?>
</div>

No comments:

Post a Comment