How to specify encoding during csv file process 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 is from the php manual, but I have not seen where to specify the encoding (e.g. utf8 or so)

+2
source share
3 answers

Try changing the locale.

As shown in the manual example below, you gave:

Note. This function is taken into account when setting the locale. If LANG is, for example, en_US.UTF-8, single-byte encoded files are not read correctly by this function.

Suggested approach for comments on the same page :

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

From setlocale():

RFC 1766 ISO 639. . [& hellip;] Windows setlocale(LC_ALL, '') / ( ).

+3

UTF . UTF-8 U + FEFF, , , - 0xef, 0xbb 0xbf - . UTF-16 . UTF-8 .

, . , .

$str = file_get_contents('file.utf8.csv');
$bom = pack("CCC", 0xef, 0xbb, 0xbf);
if (0 == strncmp($str, $bom, 3)) {
    echo "BOM detected - file is UTF-8\n";
    $str = substr($str, 3);
}

0

:

<?php
$handle = fopen ("specialchars.csv","r");
echo '<table border="1"><tr><td>First name</td><td>Last name</td></tr><tr>';
while ($data = fgetcsv ($handle, 1000, ";")) {
        $data = array_map("utf8_encode", $data); //added
        $num = count ($data);
        for ($c=0; $c < $num; $c++) {
            // output data
            echo "<td>$data[$c]</td>";
        }
        echo "</tr><tr>";
}
?>
0
source

Source: https://habr.com/ru/post/1728168/


All Articles