LoginSignup
1
1

More than 3 years have passed since last update.

Goodby/CSV 大量にデータをインポートすると、マルチバイト文字列が欠落する場合がある

Posted at

自分用の備忘録

何が問題か

私が教えてほしいです。

大量に(400行ぐらい)データをインポートすると、1~数行、
日本語文字列が一文字(3バイト分)だけ欠落するという事象が発生した

原因は不明。誰か教えて

直し方

これを

$config->setFromCharset("UTF-8");

こうすれば直った

$config->setFromCharset(NULL);

ソースコード

    /**
     * Import Csv By Goodby\CSV Parser
     * このメソッドはCSVの読み込みのみを担当し、加工はコントローラー側に任せる想定
     *
     * @param  string $filePath
     * @return array
     * @link https://github.com/goodby/csv
     * @link https://nori-life.com/laravel-csv-import-goodbycsv/
     */
    public function import($filePath)
    {
        // variable definition
        $rows = array();

        // goodby csv configuration
        $config = new LexerConfig();
        $config->setDelimiter(","); // e.g. [",", "\t"]
        $config->setEnclosure('"'); // e.g. ["'", '"']
        $config->setEscape("\\");

        // UTF-8にすると、大量にデータを読み込んだ際に、マルチバイト文字列が欠落する場合がある模様
        //$config->setFromCharset("UTF-8"); // e.g. [NULL, "UTF-8", "SJIS-win", "EUC-JP"]
        $config->setFromCharset(NULL); // e.g. [NULL, "UTF-8", "SJIS-win", "EUC-JP"]

        $config->setToCharset("UTF-8"); // e.g. [NULL, "UTF-8", "SJIS-win", "EUC-JP"]
        $config->setIgnoreHeaderLine(TRUE);

        // format csv
        $interpreter = new Interpreter();
        $interpreter->addObserver(function(array $row) use (&$rows){
            $rows[] = $row;
        });

        // parse csv
        $lexer = new Lexer($config);
        $lexer->parse($filePath, $interpreter); // parsed csv data into $rows here.

        return $rows;
    }
1
1
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1