郵便番号データからinsert文生成スクリプト

例の郵便番号データ(KEN_ALL.CSV)をDBにinsertしまくるSQL生成スクリプトPHPで書いたかも。
テーブル定義は適当かも。

<?php
    /**
    * 郵便番号データからinsert文生成スクリプト
    * 
    * -- テーブル定義
    * create table zip_codes
    * (
    *     zip_code_id int auto_increment,
    *     zip_code varchar(10) binary not null,
    *     state varchar(20) binary not null,
    *     city varchar(60) binary not null,
    *     town_area varchar(60) binary null,
    *     primary key(zip_code_id)
    * )
    * ENGINE=InnoDB DEFAULT CHARACTER SET = utf8
    * ;
    * 
    * http://www.post.japanpost.jp/zipcode/dl/kogaki-zip.html
    */
    $read_file  = "./KEN_ALL.CSV";
    $wrtie_file = './insert_ken_all.sql';

    $i = 0;
    $zip_code_mst = array();    // 重複チェック用

    $fh_w = fopen($wrtie_file, "w");
    $fh_r = fopen($read_file, "r");
    if ($fh_r) {
        while (($row = fgets($fh_r, 4096)) !== false) {
            $i++;
            $data = mb_convert_encoding($row, 'utf8', 'sjis');
            
            $data = rtrim($data);
            $cols = explode(',', $data);
            
            $zip_code   = str_replace('"', '', $cols[2]);    // 郵便番号

            // すでに同じ郵便番号を処理していればスルー
            if (array_key_exists($zip_code, $zip_code_mst)) {
                continue;
            }
            $zip_code_mst["$zip_code"] = 1;

            $state      = str_replace('"', '', $cols[6]);    // 都道府県
            $city       = str_replace('"', '', $cols[7]);    // 市区
            $town_area  = str_replace('"', '', $cols[8]);    // 町村
            $town_area  = preg_replace('/以下に掲載がない場合/', '', $town_area);
            $town_area  = preg_replace('/^.+の次に番地がくる場合$/', '', $town_area);
            $town_area  = preg_replace('/^.+一円$/', '', $town_area);
            $town_area  = preg_replace('/^(.+)(.+/', '${1}', $town_area);
            
            $sql = sprintf(
                "insert into zip_codes (zip_code, state, city, town_area) values('%s', '%s', '%s', '%s');\n",
                $zip_code,
                $state,
                $city,
                $town_area
            );
            fwrite($fh_w, $sql);
        }
        if (!feof($fh_r)) {
            echo "Error: unexpected fgets() fail\n";
        }
        fclose($fh_r);
    }

    fclose($fh_w);