asp 读取 utf-8格式文档并生成utf-8格式文档的乱码问题


今天在对搜索吧的程序进行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" %>
你的页面不要忘记这几行代码了,否则你读取后输出的内容是乱码。

« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3