9

how can I convert a string, that contains latin1 characters to utf8?

The string is a document, that is opened by open-uri and that contains these special characters.

Best regards

brainfck
  • 9,286
  • 7
  • 28
  • 29

2 Answers2

16

Iconv

require 'iconv'
i = Iconv.new('UTF-8','LATIN1')
a_with_hat = i.iconv("\xc2")
Jonathan Feinberg
  • 44,698
  • 7
  • 80
  • 103
4

Judging by your tags, I guess you want something like this:

require 'rubygems'
require 'open-uri'
require 'nokogiri'
require 'iconv'

file = open(your_uri)
doc = Nokogiri::HTML(Iconv.conv('utf-8', 'latin1', file.readlines.join("\n")))
doc.xpath(your_xpath)

If you're not sure what charset the uri uses, you can use file.charset to get the charset instead of 'latin'.

andre-r
  • 2,685
  • 19
  • 23