Hello!
On Fri, Aug 9, 2013 at 5:55 PM, 李恒 wrote:
> LuaXML遇到中文太坑爹了,
> 搞了一晚上,快崩溃了,烦请春哥指点下啦。。。。
>
可以考虑在你的 Lua 代码中直接通过 LuaJIT FFI 使用 libxml2 这样比较成熟的 C 库:
http://luajit.org/ext_ffi_tutorial.html
http://www.xmlsoft.org/
另外,建议在 openresty
中文邮件列表里面讨论这样的问题:https://groups.google.com/group/openresty
这样你或许可以得到更多更快的帮助。同时抄送给该列表。
Best regards,
-agentzh
> 这样做:
> xml = require("xml")
> ngx.print(xml.str(xml.eval([[<?xml version="1.0" encoding="utf-8"?><INFO
> name="你好,春哥"/>]])))
> 输出:
>
> <INFO
> name="你好,春哥"
> />
>
>
> 这么做:
> utf = require("utf8")
> xml = require("xml")
> ngx.print(string.gsub(xml.str(xml.eval([[<?xml version="1.0"
> encoding="utf-8"?><INFO name="你好,春哥"/>]])), '&#(%d+);', utf.to_utf8))
> 输出:
>
> <INFO name="ä½ å¥½ï¼Œæ˜¥å“¥" />
>
>
>
> utf8.lua:
> function tail(n, k)
> local u, r=''
> for i=1,k do
> n,r = math.floor(n/0x40), n%0x40
> u = char(r+0x80) .. u
> end
> return u, n
> end
>
> function to_utf8(a)
> local n, r, u = tonumber(a)
> if n<0x80 then -- 1 byte
> return char(n)
> elseif n<0x800 then -- 2 byte
> u, n = tail(n, 1)
> return char(n+0xc0) .. u
> elseif n<0x10000 then -- 3 byte
> u, n = tail(n, 2)
> return char(n+0xe0) .. u
> elseif n<0x200000 then -- 4 byte
> u, n = tail(n, 3)
> return char(n+0xf0) .. u
> elseif n<0x4000000 then -- 5 byte
> u, n = tail(n, 4)
> return char(n+0xf8) .. u
> else -- 6 byte
> u, n = tail(n, 5)
> return char(n+0xfc) .. u
> end
> end