Home > Article > PHP Framework > laravel import excel Chinese is not displayed
In Laravel, using Maatwebsite/Laravel-Excel is a very convenient way to process Excel files. However, sometimes when the imported Excel file contains Chinese, Laravel fails to display the Chinese characters in the database correctly. This article will explore this problem and provide some solutions.
Problem description
When using Maatwebsite/Laravel-Excel to import a table into the Laravel application, sometimes Chinese characters will be garbled or displayed incorrectly. This problem usually occurs in the following situations:
Solution
In Laravel, the database encoding is related to the AppServiceProvider.php file. You can set the database encoding in this file. If you are using a MySQL database, you can set it in this file:
use IlluminateSupportServiceProvider;
use IlluminateSupportFacadesSchema;
class AppServiceProvider extends ServiceProvider
{
public function boot() { Schema::defaultStringLength(191); DB::statement('SET NAMES utf8mb4'); DB::statement('SET CHARACTER SET utf8mb4'); }
}
In the above code, we have set the database encoding to utf8mb4, and setting the encoding in the file to be the same as the Excel file can solve the problem.
If the encoding method in your Excel file is inconsistent with the actual encoding method, then the problem of Chinese garbled characters will occur when importing. Therefore, before importing the Excel file, we need to ensure that the Excel file is encoded correctly. A simple method is:
Before opening the Excel file, save it as a TXT file and then import the TXT file. This will ensure that the encoding is correct.
For example:
$reader = MaatwebsiteExcelExcel::load('excel.xls')->toCsv('excel.csv');
$csvData = file_get_contents('excel .csv');
$csvData = mb_convert_encoding($csvData, 'UTF-8', 'UTF-8');
$csvFile = fopen('excel.csv', 'w');
fwrite($csvFile, $csvData);
fclose($csvFile);
$reader = MaatwebsiteExcelExcel::load('excel.csv')->get();
at In this example, we convert the Excel file to a CSV file and then convert it to UTF-8 encoding. Please note that this approach is not the best approach and you may need to make more adjustments to ensure the correctness of your data.
Conclusion
Dealing with the problem of Chinese characters is not an easy task. However, after the discussion in this article, we have understood the basic solutions. If you still encounter problems with Chinese character import errors, please keep checking your database encoding and Excel file encoding and make necessary adjustments.
The above is the detailed content of laravel import excel Chinese is not displayed. For more information, please follow other related articles on the PHP Chinese website!