1
votes

The Swedish alphabet contains the letters

åäö

I try to read a csv file with the PHP function fgetcsv but I get encoding problems and the special characters are not correctly interpreted.

I open the file with fopen ( $filePath, "r" ) and I do not speciay any encoding that anywhere in PHP that I am aware of. Everything else in my application works fine regarding to encoding.

When I open the target csv file in open office suite I can select encoding. If I select Unicode(UTF-8) the special characters can not be displayed. If I select some ISO-8859, the letters are correctly displayed.

I have been playing around with utf8_decode, utf8_encode, mb_convert_encoding, iconv and setlocale with no luck.

I know what encoding is but I do not understand this case. It would be nice with a solution and a good explanation of what is going on here.

I guess my file is ISO-8859-* encoded

How can I parse the file correctly so I can make use of its content in PHP?

2

2 Answers

1
votes
Try this
    Å

    Å

    å

    å

    Ä

    Ä

    ä

    ä

    Ö

    Ö

    ö

    ö
1
votes

you could encoded your file, for example using htmlentities.

for example, with this litle code, i encoded the swedish file to ISO-8859-1,

$file = fopen("translations-sv.csv", "r");
$new_file = fopen("file_encoded.csv", "w");
while(!feof($file)) {

$line=fgets($file);
$line = str_replace(";", ",",$line);  //replace all ';' to ','
$encoded_line=htmlentities($line,ENT_QUOTES,'ISO-8859-1');

fwrite($new_file, $encoded_line);
}

fclose($file);
fclose($new_file);

Swedish.csv

title_orders;Beställningar
title_monthly_sales;Månadsförsäljning
title_settings;Inställningar

file_encoded.csv

title_orders,Beställningar
title_monthly_sales,Månadsförsäljning
title_settings,Inställningar

and, to compare,

$new_file = fopen("file_encoded.csv", "r");

$word_to_find="Orderslutförande";
while (!feof($new_file) ) {

    $line_of_text = fgetcsv($new_file, 1024,",");
if($word_to_find==$line_of_text[1]) 
 echo $line_of_text[1]." is the same to $word_to_find<br>";
}
fclose($new_file);