开发者

Import CSV from url address and export as XML -- Rails

Two questions:

  1. How can I import a file from a web address, without a form?

    Example: Organisation.import(:from => 'http://wufoo.com/report.csv')

  2. How can I use xml builder without pulling from the db?

More Info

My company uses wufoo for web forms. The data from wufoo is e开发者_运维百科xported as csv files. To get the data into my company's cms, it needs to be formatted as xml. I don't need to store any of the data, aside from the url to the csv file. I thought this might work well as a simple rails app.


Use open-uri (http://www.ruby-doc.org/stdlib/libdoc/open-uri/rdoc/) to fetch the file, and ruby's csv library to parse it. Or, use csv-mapper which is nice and simple (http://csv-mapper.rubyforge.org/).


Here is a way:

require 'rio'
require 'fastercsv'

url = 'http://remote-url.com/file.csv'
people = FasterCSV.parse(rio(url).read)

xml = ''
1.upto(people.size-1) do |row_idx|
  xml << "  <record>\n"
  people[0].each_with_index do |column, col_idx|
    xml << "    <#{column.parameterize}>#{people[row_idx][col_idx]}</#{column.parameterize}>\n"
  end
  xml << "  </record>\n"
end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜