在Laravel中更改导入的文件编码

时间:2017-10-13 06:46:45

标签: php laravel laravel-5 encoding laravel-5.1

经过对论坛的深入研究,我在这里发布了我的问题,因为没有一个主题符合我的情况。

我正在Laravel中导入文件(csv或Excel),在我的控制器中我使用Input::file('file_name')来获取文件。

用户必须从界面中的选择中选择他的编码。

所以我的问题是,我想将文件编码更改为用户设置的。

我使用了mb_detect_encoding函数但是如果我检查后总是这样,我总是有ASCII编码......

这是我的代码:

$encoding = Input::get('encoding');
$fileContent = \File::get($importFile);
$importFile = Input::file('import_file');
$enc = mb_detect_encoding($fileContent , mb_list_encodings(), true);
if ($enc !== $encoding){
    \File::put($importFile,mb_convert_encoding(\File::get($importFile), $encoding, $enc));
}

1 个答案:

答案 0 :(得分:1)

mb_detect_encoding($str)

According to the docs

  

检测字符串str

中的字符编码

according to the Laravel 5.1 docs用于文件上传:

  

文件方法返回的对象是Symfony \ Component \ HttpFoundation \ File \ UploadedFile类的实例

因此,在上面的代码中,$importFile是一个类的实例。将其传递给mb_detect_encoding将不会为您提供实例所代表的文件的编码。

要检查文件的内容的编码,您需要先加载该内容:

$importFile = Input::file('import_file');
$fileContent = file_get_contents($importFile->path());

然后,您可以将内容传递给mb_detect_encoding()并检查编码:

$enc = mb_detect_encoding($importFile, mb_list_encodings(), true);