Import csv with special encoding via Laravel Excel

Tram Ho

I. Introduction

  • As the title of this article, this time I will show you how to do import csv via Laravel Excel
  • This problem I encountered and took a few days, because when using this package, according to research, only set one encoding right (spicy), when setting this QA, use another to import, then to the customer … I told them they can only use one? So that’s not possible ….
  • The excel.php config file of Laravel Excel has an attribute of input_encoding , here Laravel Excel has the default UTF-8 encoding.
  • But in Japan they often use Shift-JIS (or also others like UJIS, ANSI …)
  • As usual, of course, I also set SJIS to the above config, everything works fine for a few days, then the guests use files with other encoding. : v

II. Problem solving.

After a few times, I was too lucky to think that I would detect the encoding format, they would use Turkish, Greek … until teencode I could do it, too, through simple thought. And yet also found a way ❤️ And here is my workaround


  • Line 1: function file_get_contents will read the contents of the file.
  • Line 2: function mb_detect_encoding will dectect encoding based on mb_list_encodings and return the encoding of the uploaded file
  • Line 3: will interfere with the config at that time – ie n will change r after performing the function will return to the same way (other than overwriting the file).

III. Upload the file

  • I want to share what I find out so it looks a bit short ? ) so I will guide how to upload files as well.
  • This package is very nice in that it has made chunk files for me, so it has also limited the reading of heavy files (You should use)
  • Controller

  • The setInputEncoding function will be run before Excel’s Laravel can read the uploaded file.
  • Here if you do not use the queue but want to display a validate error during import then do as you would the catche section.
  • File Import

  • Here I do not use queue, but if you use queue then if validated error can be taken from database (queue database) …. or use other types of queue.
  • The chunkSize function I found very beneficial in this package, it is really necessary if any project saves k queue usage (like my project =))).

III. Finished

  • Above is how I work when importing csv, with the encoding that is not really many users and popular. Hope to help you who are having problems like me
  • Another small problem that can occur while uploading is that I use ubuntu when creating the csv file and sending it to the guest (using the window), it may fall into the case that the computer automatically changes the file’s extension (csv – > xls) so you can also note this problem when validating the bared file (lol)
Share the news now

Source : Viblo