Php可以';t读取带有Shift JIS编码的文件


Php can't read file with Shift JIS encoding

在服务器上运行时,我在读取编码为Shift_JIS的csv文件时出错。我试着遵循下面的代码:

function readFile($file)
{
    setlocale(LC_ALL, 'ja_JP.sjis');
    $ret = array();
    $fp = fopen($file, 'r');
    while ($line = fgetcsv($fp)) {
        mb_convert_variables('utf-8', 'sjis-win', $line);
        $ret[] = $line;
    }
    fclose($fp);
    return $ret;
}

当在localhost中时,我没有任何问题,但当我在服务器上运行时,并没有正确的格式。

这是在localhost(XAMPP)上运行的文件的内容:

阵列

[0] => Array
    (
        [0] => カテゴリID
        [1] => ブランドID
        [2] => サイズID
        [3] => カラーID
        [4] => 状態
        [5] => 商品名
        [6] => 価格(税込)
        [7] => 商品説明
        [8] => 在庫数
        [9] => 送料個別設定
        [10] => 公開状態
    )

)

但在服务器上运行(centos):

阵列(

[0] => Array
    (
        [0] => JテゴリID
        [1] => uランドID
        [2] => TイズID
        [3] => JラーID
        [4] => 
        [5] => i名
        [6] => i(税込)
        [7] => i説明
        [8] => 
        [9] => 
        [10] => J状態
    )

)

请帮帮我!

如果可以更新PHP版本,那么您可以将PHP版本至少更新到5.6,那么问题就解决了。

如果没有,请执行以下技巧:

function getFilePointerUTF8($target_file){
    $current_locale = setlocale(LC_ALL, '0'); // Backup current locale.
    setlocale(LC_ALL, 'ja_JP.UTF-8');
    // Read the file content in SJIS-Win.
    $content = file_get_contents($target_file);
    // Convert file content to SJIS-Win.
    $content = mb_convert_encoding($content, "UTF-8", "SJIS-win");
    // Save the file as UTF-8 in a temp location.
    $fp = tmpfile();
    fwrite($fp, $content);
    rewind($fp);
    setlocale(LC_ALL, $current_locale); // Restore the backed-up locale.
    return $fp;
}

使用:

$fp = $this->getFileReaderUTF8("[your_file_location]"); // Ex: "~/data.csv"
$utf8_CSV_content = fgetcsv($fp);