doucheng7534 2013-01-28 14:03
浏览 207
已采纳

字符编码utf8到latin1,解释这两个字符

I have a database which uses latin-1 and a PHP application which is utf-8.

I have strings in the database like this:

'Société' which should be Société

'€1bn' which should be €2bn.

When I print the faulty characters to screen with PHP's ord(), from the returning data in the db, it prints 195 and 226.

Could somebody explain why this is happening (why saving like this and why characters being read as they are) and if I can reverse it.

  • 写回答

2条回答 默认 最新

  • dpjuppr1361 2013-01-28 14:06
    关注

    The WHY:

    1) é is unicode 233 (as the browser reads it).
    é utf8 bytes converted into latin1 chars bytes is à ©. This is why it appears like this in the database.
    à © is recognised as à which is code point 195. Hence why you see that.

    2) € is unicode 8364.
    € utf8 bytes converted into latin1 chars bytes is â <82> ¬. Again this is why they appear like this in the db.
    â <82> ¬ is recognised as â which is code point 226. Again this is why you see this.

    That is why you see those values from ord() and why the characters are stored in that manner in a latin-1 database.

    Reverse:

    To reverse it we need Latin-1 char bytes to UTF8 bytes.

    If we try it:
    â is 226. Converted latin-1 to utf8 produces â.
    à is 195. Converted latin-1 to utf8 produces Ã.

    Problem:

    The problem is Latin-1 has less characters than utf-8 (by a long way).
    Latin1 single-byte stream and UTF8 multi-byte char stream so 1 char in utf8 could produce up to 4 chars for latin1.
    So the UTF-8 to Latin-1 conversion produces faulty characters.
    Latin1 back to utf8 is not possible.

    Solution:

    IF you are unable to change the character set of your database I could suggest encoding special characters in the database in their character entity before writing them (so the db can stay as latin1 and app as utf8 as both can understand html entities) e.g. umlaut as &Auml;.
    It could be done using PHPs html_entity_decode() combined with mb_detect_encoding() to detect and convert specific characters.

    References:

    See ltf.ed.ac.uk for the utf8 char bytes to latin1 bytes:
    http://www.ltg.ed.ac.uk/~richard/utf-8.cgi?input=%C3%96&mode=char

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)