標籤雲是部落格與 CMS 常見的導航元素,特徵為字體大小不一、顏色豐富,視覺上呈現標籤熱門度分佈。本文詳解 PHP 後端生成策略、前端整合方式與效能優化建議。
<a> 或 <span> 標籤,含 style 內聯樣式/**
* 生成隨機十六進位顏色代碼
* @return string 格式:#RRGGBB
*/
function getRandomColor(): string {
$hexChars = '0123456789ABCDEF';
$color = '#';
for ($i = 0; $i < 6; $i++) {
$color .= $hexChars[random_int(0, 15)]; // PHP 7+ 密碼學安全隨機
}
return $color;
}
/**
* 生成隨機字體大小(含單位)
* @param int $min 最小像素
* @param int $max 最大像素
* @return string 如 "16px"
*/
function getRandomFontSize(int $min = 12, int $max = 24): string {
return random_int($min, $max) . 'px';
}
class TagCloudGenerator {
private $tags = [];
private $minSize = 12;
private $maxSize = 28;
private $unit = 'px';
public function __construct(array $tags, int $minSize = 12, int $maxSize = 28) {
// 去重並標準化
$this->tags = array_unique(array_map('trim', $tags));
$this->minSize = $minSize;
$this->maxSize = $maxSize;
}
public function setSizeRange(int $min, int $max): self {
$this->minSize = $min;
$this->maxSize = $max;
return $this;
}
/**
* 生成標籤雲 HTML
* @param string $baseUrl 標籤連結基礎 URL,如 "/tag/"
* @param bool $weighted 是否依權重調整大小(需標籤帶權重陣列)
* @return string
*/
public function render(string $baseUrl = '', bool $weighted = false): string {
$html = '';
$count = count($this->tags);
if ($weighted && $this->hasWeights()) {
$maxWeight = max(array_column($this->tags, 'weight'));
$minWeight = min(array_column($this->tags, 'weight'));
}
foreach ($this->tags as $tag) {
$name = is_array($tag) ? $tag['name'] : $tag;
$url = $baseUrl . urlencode($name);
// 計算字體大小
if ($weighted && isset($tag['weight'])) {
$ratio = ($maxWeight - $minWeight) > 0
? ($tag['weight'] - $minWeight) / ($maxWeight - $minWeight)
: 0.5;
$size = $this->minSize + ($this->maxSize - $this->minSize) * $ratio;
} else {
$size = random_int($this->minSize, $this->maxSize);
}
$color = $this->getRandomColor();
$html .= sprintf(
'%s',
$url, $size, $this->unit, $color, htmlspecialchars($name), htmlspecialchars($name)
);
}
$html .= '';
return $html;
}
private function hasWeights(): bool {
return !empty($this->tags) && is_array(reset($this->tags)) && isset(reset($this->tags)['weight']);
}
private function getRandomColor(): string {
return '#' . bin2hex(random_bytes(3)); // PHP 7+ 最簡寫法
}
}
// 使用範例
$tags = ['PHP', 'Laravel', 'MySQL', 'Redis', 'Docker', 'Kubernetes', 'Vue.js', 'API'];
$cloud = new TagCloudGenerator($tags);
echo $cloud->render('/tag/');
PHP 為伺服器端語言,每次請求執行 rand() 會消耗 CPU。對於高流量站點,建議:
storage/cache/tagcloud.html)include 'tagcloud.html' 或前端 AJAX 載入// 快取寫入範例
$cacheFile = __DIR__ . '/../storage/cache/tagcloud.html';
$html = $cloud->render('/tag/');
file_put_contents($cacheFile, $html);
// 模板中引入
// <div id="tag-cloud"><?php include $cacheFile; ?></div>
將標籤資料以 JSON 傳給前端,由 JavaScript 渲染,優點:
知名函式庫:jQCloud、TagCanvas (Canvas 3D 效果)
color-contrast-checker 驗證)title 屬性與語意化 <a>,利於搜尋引擎爬蟲