Created
February 20, 2015 11:12
-
-
Save kiarina/3223aedbe9b44156ec72 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
//-------------------------------------------------- | |
// 引数で受け取ったCSVかTSVファイルをJSONに変換する | |
// ファイルのフォーマットは拡張子で判断する | |
// 出力ファイル名が指定されていない場合は、 | |
// 入力ファイル名の拡張子を変更して出力する | |
// | |
// $ php convertJson.php -f master.tsv -o master.json | |
//-------------------------------------------------- | |
function getDataListFromCsv($path, $delimiter = ",") { | |
$dataList = array(); | |
$fp = fopen($path, 'rt'); | |
if ($fp === false) { | |
echo "can not open file. $path" . PHP_EOL; | |
exit(1); | |
} | |
$columns = fgetcsv($fp, 0, $delimiter); | |
while ($row = fgetcsv($fp, 0, $delimiter)) { | |
// キャスト | |
foreach ($row as &$value) { | |
if (is_numeric($value)) { | |
$value = floatval($value); | |
} | |
} | |
unset($value); | |
// カラム名と値を結合 | |
$data = array_combine($columns, $row); | |
$dataList[] = $data; | |
} | |
fclose($fp); | |
return $dataList; | |
} | |
function usage() { | |
echo <<<EOT | |
php convertJson.php -f <input_file> [-o <output_file>] | |
EOT; | |
} | |
//-------------------------------------------------- | |
// main 処理はここから | |
//-------------------------------------------------- | |
$options = getopt("f:o:"); | |
// 入力ファイルを取得 | |
if (!isset($options["f"])) { | |
usage(); | |
exit(1); | |
} | |
$inputFile = $options["f"]; | |
// 入力ファイルの形式を取得 | |
$tmp = explode(".", $inputFile); | |
$extension = end($tmp); | |
unset($tmp); | |
if ($extension == "tsv") { | |
$delimiter = "\t"; | |
} else if ($extension == "csv") { | |
$delimiter = ","; | |
} else { | |
usage(); | |
exit(1); | |
} | |
// 出力ファイルを取得 | |
if (!empty($options["o"])) { | |
$outputFile = $options["o"]; | |
} else { | |
$outputFile = str_replace($extension, "json", $inputFile); | |
} | |
// 入力ファイルから配列を生成 | |
$dataList = getDataListFromCsv($inputFile, $delimiter); | |
// JSON形式に変換 | |
$json = json_encode($dataList, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE); | |
// JSONファイルを出力 | |
$fp = fopen($outputFile, 'wt'); | |
if ($fp === false) { | |
echo "file can not open. $outputPath" . PHP_EOL; | |
exit(1); | |
} | |
fputs($fp, $json); | |
fclose($fp); | |
exit; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment