asp 讀取 utf-8格式文檔並產生utf-8格式文檔的亂碼問題_應用技巧

來源:互聯網
上載者:User
今天在對搜尋吧的程式進行utf-8修正時,發現產生的utf-8格式文檔存在著亂碼,原來檔案

create_html.asp代碼如下: 

複製代碼 代碼如下:

<%@LANGUAGE="VBSCRIPT" CODEPAGE="65001"%> 
<% 
set objrs=server.createObject("Scripting.FileSystemObject") 
conn=server.mappath("example.xml") 
set Stream=objrs.opentextfile(conn,1,true,-2)   
content=stream.readall 
Response.Write(content) 
stream.close 
%> 

        這段代碼要實現的功能是:從example.xml(utf-8格式)中讀取文字包括中文,然後輸出,但是每次輸出卻都是亂碼,這個問題著實困擾了我很久,後來還是在經典論壇“小韓”“蕭蕭小雨 ”的協助下解決了,真是感謝他們了。

        或許我一開始就是錯誤的,現在正確的代碼修改後如下,用了“蕭蕭小雨”給的代碼,包括了用讀取的內容產生新的utf-8格式文檔。詳細代碼如下:

複製代碼 代碼如下:

<%@LANGUAGE="VBSCRIPT" CODEPAGE="65001"%> 
<% Response.CodePage=65001%>  
<% Response.Charset="UTF-8" %>  
<% 
'申明變數 
dim read_path,write_paht,content 
'----讀取檔案內容------------------------ 
Function ReadTextFile(filePath,CharSet) 
       dim stm 
       set stm=Server.CreateObject("adodb.stream")  
       stm.Type=1 'adTypeBinary,按位元據讀入 
       stm.Mode=3 'adModeReadWrite ,這裡只能用3用其他會出錯 
       stm.Open  
       stm.LoadFromFile filePath 
       stm.Position=0 '把指標移回起點 
       stm.Type=2 '文本資料 
       stm.Charset=CharSet 
       ReadTextFile = stm.ReadText 
       stm.Close  
       set stm=nothing  
End Function 

'----寫入檔案------------------------ 
Sub WriteTextFile(filePath,fileContent,CharSet) 
       dim stm 
       set stm=Server.CreateObject("adodb.stream")  
       stm.Type=2 'adTypeText,文本資料 
       stm.Mode=3 'adModeReadWrite,讀取寫入,此參數用2則報錯 
       stm.Charset=CharSet 
       stm.Open  
       stm.WriteText fileContent   
       stm.SaveToFile filePath,2 'adSaveCreateOverWrite,檔案存在則覆蓋 
       stm.Flush  
       stm.Close  
       set stm=nothing  
End Sub 
'要讀取的檔案路徑 
read_path = Server.MapPath("example.xml") 
'要寫入的檔案路徑 
write_path = Server.MapPath("example.asp") 
'讀取的檔案內容 
content = ReadTextFile(read_path,"utf-8") 
'輸出讀取的檔案 
Response.Write(content) 
'開始寫入 
call WriteTextFile(write_path,content,"utf-8") 
%> 


這段代碼相當實用,對於產生utf-8格式靜態頁十分有用,一些必要的解釋我也註明了,需要注意的是:

複製代碼 代碼如下:

<%@LANGUAGE="VBSCRIPT" CODEPAGE="65001"%> 
<% Response.CodePage=65001%>  
<% Response.Charset="UTF-8" %>  
你的頁面不要忘記這幾行代碼了,否則你讀取後輸出的內容是亂碼。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.