Force strings to UTF-8 from any encoding

前端 未结 4 1360
不知归路
不知归路 2020-12-13 13:36

In my rails app I\'m working with RSS feeds from all around the world, and some feeds have links that are not in UTF-8. The original feed links are out of my control, and i

4条回答
  •  情歌与酒
    2020-12-13 14:03

    Iconv

    require 'iconv'
    i = Iconv.new('UTF-8','LATIN1')
    a_with_hat = i.iconv("\xc2")
    

    Summary: the iconv gem does all the work of converting encodings. Make sure it's installed with:

    gem install iconv
    

    Now, you need to know what encoding your string is currently in as Ruby 1.8 treats Strings as an array of bytes (with no intrinsic encoding.) For example, say your string was in latin1 and you wanted to convert it to utf-8

    require 'iconv'
    
    string_in_utf8_encoding = Iconv.conv("UTF8", "LATIN1", string_in_latin1_encoding)
    

提交回复
热议问题