Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exporting CSV with League/CSV doesn't encode umlauts

I am exporting a model in Laravel 5.7, using the League/CSV package:

public function export(Request $request)
{
    $people = Person::all();
    $location = 'export.csv';
    $csv = Writer::createFromPath($location, 'w');
    $csv->setOutputBOM(Writer::BOM_UTF8);
    $csv->setDelimiter(';');
    foreach ($people as $person) {
        $csv->insertOne($this->serializePerson($person));
    }
    return response($location);
}

protected function serializePerson($person)
{
    return [
        $person->name,
        $person->age,
    ];
}

This creates the export.csv file ok, but any umlauts are rendered incorrectly (e.g. as ö). I would have thought setting the BOM would have solved this. Does anyone have a solution?

EDIT: The problem was not the export, it was Mac Excel displaying the umlaut incorrectly. See my answer below.

like image 547
GluePear Avatar asked Nov 07 '22 19:11

GluePear


1 Answers

My question was badly formulated, but I'll leave the answer here in case anyone else has the same problem. The file was in fact being correctly exported: if I opened it in a text editor the umlaut was correctly formed.

To get it working properly in Excel (on a Mac) I had to:

  1. Open an empty worksheet
  2. Data > Get External Data > Import Text File...
  3. From the File origin dropdown, select "Unicode (UTF-8)"
like image 122
GluePear Avatar answered Nov 13 '22 19:11

GluePear