為文章自動生成標籤 (Tags) 能提升 SEO 與站內搜尋體驗。利用 Discuz! 開放的關鍵詞提取 API (keyWord.discuz.com/related_kw.html),傳入標題與內容,即可取得 XML 格式的建議關鍵詞。本文封裝為 ShowTags(strTitle, strContent) 函數,可直接套用於 ASP 發文/編輯流程。
https://keyWord.discuz.com/related_kw.htmltitle (URLEncode)、content (URLEncode)、ics=utf-8 (輸入編碼)、ocs=utf-8 (輸出編碼)<root>
<info><count>N</count></info>
<item><kw>關鍵詞1</kw></item>
<item><kw>關鍵詞2</kw></item> ...
</root>
<%@ LANGUAGE="VBSCRIPT" CODEPAGE="65001" %>
<%
Option Explicit
Response.Charset = "UTF-8"
Session.CodePage = 65001
Server.ScriptTimeout = 9999
'============================================================
' 功能: 自動提取文章標籤/關鍵字
' 參數: strTitle (標題), strContent (內容)
' 回傳: 0=無匹配, 否則回傳「半形逗號分隔」的標籤字串
' 依賴: Microsoft.XMLDOM (MSXML 3.0+)
'============================================================
Function ShowTags(ByVal strTitle, ByVal strContent)
Dim xml, objNodes, XMLPath, i, countNode
On Error Resume Next
strTitle = Server.URLEncode(strTitle)
strContent = Server.URLEncode(strContent)
XMLPath = "https://keyWord.discuz.com/related_kw.html?title=" & strTitle & _
"&content=" & strContent & "&ics=utf-8&ocs=utf-8"
Set xml = Server.CreateObject("Microsoft.XMLDOM")
With xml
.async = False
.resolveExternals = False
.setProperty "ServerHTTPRequest", True ' 允許伺服器端 HTTP 請求
.load XMLPath
End With
If Err.Number <> 0 Then
ShowTags = 0
Set xml = Nothing
Exit Function
End If
Set countNode = xml.getElementsByTagName("info")(0).selectSingleNode("count")
If countNode Is Nothing Or CInt(countNode.Text) = 0 Then
ShowTags = 0
Else
Set objNodes = xml.getElementsByTagName("item")
For i = 0 To objNodes.length - 1
ShowTags = ShowTags & Trim(objNodes(i).selectSingleNode("kw").Text) & ","
Next
' 移除尾端逗號
If Len(ShowTags) > 0 Then ShowTags = Left(ShowTags, Len(ShowTags) - 1)
Set objNodes = Nothing
End If
Set xml = Nothing
On Error GoTo 0
End Function
'=== 使用範例 ===
Response.Write "標籤:" & ShowTags("Web 開發相關技術探討", "ASP、PHP、ASP.NET、資料庫設計、前端框架...")
%>
| 細節 | 處理方式 |
|---|---|
| 編碼一致性 | 頁面 CODEPAGE=65001、Session.CodePage=65001、API 參數 ics=utf-8&ocs=utf-8、Server.URLEncode 皆為 UTF-8 |
| 同步阻塞 | .async = False 確保 .load 完成才繼續 |
| 伺服器端 HTTP | .setProperty "ServerHTTPRequest", True 繞過 MSXML 預設的客戶端限制 |
| 錯誤容忍 | On Error Resume Next 包裹網路/XML 解析,失敗回傳 0 不中斷主流程 |
| 超時控制 | Server.ScriptTimeout = 9999 防止 API 回應過慢導致腳本逾時 |
若環境無法連外網或需離線運作,可改用:
SCWS、IKAnalyzer COM 版)ShowTags,結果存入 ArticleTags 欄位ArticleTags 欄位,以逗號分隔拆分顯示透過 Discuz! 關鍵詞 API 實現 ASP 自動標籤提取,僅需 30 行核心代碼,零維護成本。注意編碼一致性、網路超時與錯誤容忍。若追求完全自主可控,建議部署本地分詞服務 (Python/Jieba/Go) 供內部呼叫,架構更穩健。