首页 > 解决方案 > league/csv problem reading file with ISO-8859-1 encoding

问题描述

$data = file_get_contents($path);
$data = mb_convert_encoding($data, 'UTF-8', mb_detect_encoding($data, 'UTF-8, ISO-8859-1', true));

$csv = Reader::createFromString($data);
$csv->setDelimiter(';');
$csv->setHeaderOffset(0);

$test = $csv->getContent();

return (new Statement)->process($csv); 

When I debug and look at $test, all characters are displayed correctly (no lønn etc).

When I loop through the TabularDataReader object returned from this line:

return (new Statement)->process($csv); 

the headers are displaying incorrectly e.g "Bil lønn" (should be "Bil lønn").

Do I have to set encoding on the Statement object as well? I looked through the class, but couldn't find any functions related to encoding.

标签: phpcharacter-encoding

解决方案


I've had the same issue with league/csv and ISO-8859-1 encoding. Try this workaround:

$data = file_get_contents($path);

if (!mb_check_encoding($data, 'UTF-8')) {
    $data = mb_convert_encoding($data, 'UTF-8');
}

$csv = Reader::createFromString($data);
$csv->setDelimiter(';');
$csv->setHeaderOffset(0);

$test = $csv->getContent();

return (new Statement)->process($csv); 

推荐阅读