I have a table that has some Unicode in it. I know that the Unicode data is fine as it comes out as JSON on our webserver just fine. But for some reason the CSV that I’m generating is ending up mangled. Here’s our current code:
my $csv = Text::CSV->new ({ eol => "\015\012" });
open my $fh, '>:encoding(utf8)', 'Foo.csv';
my $sth = $dbh->prepare("SELECT * FROM Foo");
$sth->execute();
my $i = 0;
while (my $row = $sth->fetchrow_hashref) {
$csv->print($fh, [keys %$row]) if $i == 0;
$csv->print($fh, [values %$row]);
$i++;
}
Any ideas?
Aside from the encoding issue, I don’t think there’s any guarantee that
valueswill always give the fields in the same order. You might be getting a different hashref fromfetchrow_hashrefeach time you call it. The solution to that is to usefetchrow_arrayref.Text::CSV recommends Text::CSV::Encoded:
Or, if you don’t want to have to install a new module: