2011年6月8日水曜日

fgetcsv setlocale に頼らない CSV ファイルの読み込み関数

fgetcsv でCSVが簡単に読み込める場合は問題有りませんが、setlocaleでいろいろごにょごにょしないと文字化けにハマるし、設定に依存するのでサーバが変わると不具合が発生したりと、安心してつかえません。

fgetsで1行もってきてexplodeで切ればいいかというとCSV中に改行が入っていたり、ダブルクォーテーション文字列中に入っていたりする場合うまく行きません。

そこで、全てを網羅してきちんとCSVの1レコード分を読み込む関数を作りました。

    /*
     * Load CSV Line
     *         with CR+LF included in the columns
     *     Licenced GPL Ver.2: Copyright(c) Yoshi Sakai @ Bluemoon inc.
     *
     *     &$handle = File pointer
     *     $fieldNumber = Field number ( Max colmuns )
     */
    function fgets_csv( &$handle, $fieldNumber=0 ){
        if ( $fieldNumber==0 || feof($handle) ) return TRUE;
        $line = fgets($handle);                                    // Load 1 line anyway
        while ( 1 ){
            // Check CR+LF in the double cuotation and load
            $str = preg_replace('/"{2}/','"', $line);
            while ( substr_count($str,'"') % 2 > 0 ){
                if (feof($handle)) break;
                $line .= fgets($handle);
                $str = preg_replace('/"{2}/','"', $line);
            }
             // Check Field number
            $str = preg_replace('/"(.*?)"/',"", $line);            // cut double cuotation
            $n = substr_count($str,',');                        // count comma
            if ( feof($handle) || $n+1 >= $fieldNumber ) break;    // Field Ok?
        }       
        return $line;
    }

0 件のコメント:

コメントを投稿