PHP Tag cloud

A PHP tag cloud class

Basic usage

include 'classes/tagcloud.php';
$cloud = new tagcloud();
$cloud->addTag("tag-cloud");
$cloud->addTag("programming");
echo $cloud->render();

Convert a string

$cloud->addString("This is a tag-cloud script, written by Del Harvey.");
$cloud->addString("I wrote this tag-cloud class because I just love writing code.");

Adding multiple tags

$cloud->addTags(array('tag-cloud','php','github'));

Removing a tag

$cloud->setRemoveTag('github');

Removing multiple tags

$cloud->setRemoveTags(array('del','harvey'));

More complex adding

$cloud->addTag(array('tag' => 'php', 'url' => 'http://www.php.net', 'colour' => 1));
$cloud->addTag(array('tag' => 'ajax', 'url' => 'http://www.php.net', 'colour' => 2));
$cloud->addTag(array('tag' => 'css', 'url' => 'http://www.php.net', 'colour' => 3));

Set the minimum length required

$cloud->setMinLength(3);

Limiting the output

$cloud->setLimit(10);

Setting the order

By tag in alphabetical order

$cloud->setOrder('tag','ASC');

By size value (calculated value)

$cloud->setOrder('size','DESC');

Using a custom field passed in (as array - see above 'more complex adding')

$cloud->setOrder('colour','DESC');

Outputting the cloud (shown above)

echo $cloud->render();

Example: Fetching tags from a database

$cloud = new tagcloud();
$getBooks = mysql_query("SELECT title FROM `tags`");
if ($getBooks) {
    while ($rowBooks = mysql_fetch_assoc($getBooks)) {
        $cloud->addTag($rowBooks['title']);
    }
}
$myCloud = $cloud->render('array');
if (is_array($myCloud)) {
    foreach ($myCloud as $key => $value) {
        echo ' <a href="./tags/'.urlencode($value['tag']).'" style="font-size: 1.'.($value['range']).'em">'.$value['tag'].'</a> ';
    }
}

Example: Fetching tags from a text file

$cloud = new tagcloud();
$f = 'tags.txt'; // Filename of the text file
if ($h = fopen($f, 'r')) {
    if (!feof($h)) {
        do {
            $c = fread($h, 4096);
            $t = explode('|', $c);
            foreach ($t as $k => $v) {
                $cloud->addTag($v);
            }
        } while (!feof($h));
    }
}
echo $cloud->render();