erlang 字符编码 <29>
用mochiweb通过网页发送中文到服务器,结果服务器显示乱码,无论打印,还是存储日志,还是再次解析出来发往客户端均是乱码,网上搜索后发现了一些问题所在:编码不一致
erlang 字符编码的文章有很多,erlang默认是用latin1,不支持中文,
如果要支持中文,需要用其他编码,unicode常用, utf8是unicode中最常用的.
eshell也要是unicode编码才可以。否则不支持中文,当然如果用linux终端,例如我用的是centos,shell用的是xshell,xshell本身的编码也要设置正确; 如果eshell设置的是latin1中文都无法输入; 见图片
这样eshell才可以正常接收和显示中文;
编码转化为unicode,使用的时候要用ts格式才可以正常显示为中文,例如io:format等;
关于ts
The Erlang compiler will interpret the code as ISO-8859-1 encoded text, which limits you to Latin characters."translation modifier" when working with Unicode texts. The modifier is "t". When applied to the "s" control character in a formatting string, it accepts all Unicode codepoints and expect binaries to be in UTF-8.
看这个例子例如 打开utf8保存的文件 文件内容如下test.file: .
其格式为erlang term,保存时选择utf8编码。
代码如下:
Erlang代码 %% read content from the file
test1() ->
{ok, } = file:consult("test.txt"),
Desc = proplists:get_value(desc, Terms),
_Author = proplists:get_value(author, Terms),
% out put the Desc and Author
DescUniBin = iolist_to_binary(Desc),
DescUniList = unicode:characters_to_list(DescUniBin),
io:format("desc bin : ~ts~ndesc bin : ~p~n",),
io:format("desc list: ~ts~ndesc list: ~p~n", ).
这样就可以显示中文,