首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

VBScript 中文與 Unicode 雙向轉換函數庫

     編輯:PHP 綜合知識

功能概覽

提供三個核心 VBScript 函數:中文轉 URL 編碼(Unicode 逃逸)、Unicode 還原為可讀文本、XMLHTTP 取遠程內容並自動解碼。

1. URLEncoding:中文轉 %XX%XX 格式

逐字符檢測,ASCII 碼 > 255 視為雙字節字符,拆解高低位組成 %HIGH%LOW 格式。

' 轉換中文為 Unicode URL 編碼
Function URLEncoding(vstrIn)
    Dim i, strReturn, ThisChr, innerCode, Hight8, Low8
    strReturn = ""
    For i = 1 To Len(vstrIn)
        ThisChr = Mid(vstrIn, i, 1)
        If Abs(Asc(ThisChr)) < &HFF Then
            strReturn = strReturn & ThisChr
        Else
            innerCode = Asc(ThisChr)
            If innerCode < 0 Then innerCode = innerCode + &H10000
            Hight8 = (innerCode And &HFF00) \ &HFF
            Low8   = innerCode And &HFF
            strReturn = strReturn & "%" & Hex(Hight8) & "%" & Hex(Low8)
        End If
    Next
    URLEncoding = strReturn
End Function

2. bytes2BSTR:Unicode 位元組還原字符串

處理 responseBody 類型資料,逐雙字節組合 Chr(High*256 + Low) 還原中文。

' 轉換 Unicode 位元組流為正常文本
Function bytes2BSTR(vIn)
    Dim i, strReturn, ThisCharCode, nextCharCode
    strReturn = ""
    For i = 1 To LenB(vIn)
        ThisCharCode = AscB(MidB(vIn, i, 1))
        If ThisCharCode < &H80 Then
            strReturn = strReturn & Chr(ThisCharCode)
        Else
            nextCharCode = AscB(MidB(vIn, i + 1, 1))
            strReturn = strReturn & Chr(CLng(ThisCharCode) * &H100 + CInt(nextCharCode))
            i = i + 1
        End If
    Next
    bytes2BSTR = strReturn
End Function

3. getText:封裝 XMLHTTP GET 請求

自動建立 MSXML2.XMLHTTP,同步請求,狀態 200 時自動調用 bytes2BSTR 解碼返回文本。

Function getText(oReq, url)
    On Error Resume Next
    If oReq Is Nothing Then Set oReq = CreateObject("MSXML2.XMLHTTP")
    If Not oReq Is Nothing Then
        oReq.open "GET", url, False
        oReq.send
        If oReq.status = 200 Then
            getText = bytes2BSTR(oReq.responseBody)
        Else
            getText = ""
        End If
    Else
        getText = ""
    End If
End Function

使用場景與注意事項

  • 經典 ASP 專案:處理 GB2312/Big5 頁面抓取、表單提交編碼轉換。
  • 編碼前提:伺服器頁面需為對應編碼(如 GB2312),否則 Asc/AscB 取值會偏差。
  • 現代替代:ASP.NET 直接用 HttpUtility.UrlEncode/UrlDecode、Encoding.GetEncoding 更穩健。
  • 錯誤處理:建議移除 On Error Resume Next,改用具體錯誤捕獲記錄日誌。

完整測試範例

<%
Dim oReq, url, encoded, decoded
url = "https://example.com/api?keyword=中文測試"
encoded = URLEncoding("中文測試")  ' 輸出 %D6%D0%CE%C4%B2%E2%CA%D4
' 假設遠程返回 Unicode 位元組流
' decoded = getText(oReq, url & "&kw=" & encoded)
Response.Write "編碼結果:" & encoded
%>
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved