Search code examples
phpfgetcsv

How to specify encoding while process csv file in PHP?


<?php
$row = 1;
$handle = fopen ("test.csv","r");
while ($data = fgetcsv ($handle, 1000, ",")) {
    $num = count ($data);
    print "<p> $num fields in line $row: <br>\n";
    $row++;
    for ($c=0; $c < $num; $c++) {
        print $data[$c] . "<br>\n";
    }
}
fclose ($handle);
?> 

The above comes from php manual,but I didn't see where to specify the encoding(like utf8 or so)


Solution

  • Try to change the locale.

    Like it says below the example in the manual you gave:

    Note: Locale setting is taken into account by this function. If LANG is e.g. en_US.UTF-8, files in one-byte encoding are read wrong by this function.

    Suggested approach by comment on the same page:

    setlocale(LC_ALL, 'ja_JP.UTF8'); // for japanese locale
    

    From setlocale():

    Locale names can be found in RFC 1766 and ISO 639. Different systems have different naming schemes for locales. […] On Windows, setlocale(LC_ALL, '') sets the locale names from the system's regional/language settings (accessible via Control Panel).