Ruby: Convert Strings from UTF-8 to LATIN1 (ISO 8859-1) with Iconv

I used VPIM to create VCards from employees in my database which stores the employee’s data UTF-8 encoded. Then I wanted to give the user the possibility to download them. And of course half of the employees’ names were corrupted because I didn’t convert them to LATIN1 (ISO 8859-1). so here’s what i came up with:

First include Iconv in your .rb file

1
require 'iconv'"

Then convert the VCard that was created with UTF-8 encoded data to LATIN1 and send it to the user’s browser

1
2
3
4
5
6
7
8
# create vcard
card = create_vcard()

# create LATIN1 encoded string from card
encoded_card = Iconv.iconv("LATIN1", "UTF-8", card.to_s).join

# and send it to the browser
send_data  encoded_card, :type => "text/vcf; charset=iso-8859-1", :filename => "contact.vcf"

That’s basically how to convert strings with Iconv.

  • http://www.facebook.com/profile.php?id=100003469741826 Vann

    Just found this issue when converting from UTF-8 to UCS-2 for a SMS gaeatwy. The mb_convert_encoding() function seems to work properly, at least in my development and live environments. P.S. OpenID login does not seem to work. I don’t know why I don’t just drop it :(