7
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

「国民の祝日」CSVを生PHPでJSONに変換

Last updated at Posted at 2017-02-23

2017/03/02 追記

フォーマットが変わってる(詳しくはこちら
ちゃんとCSVらしいCSVになってますね…、どうせなら振替休日も追加してよ


発端:内閣府の「国民の祝日」のCSVがひどい。

みんなやってそうだけど、適当に生PHPで

holiday_ja.php
<?php
date_default_timezone_set('Asia/Tokyo');
setlocale(LC_ALL, 'ja_JP.UTF-8');

// どうしてSSLで提供しないんだ…
$csv_url = 'http://www8.cao.go.jp/chosei/shukujitsu/syukujitsu.csv';

/*
 * リクエスト実行
 */
$ch = curl_init();
curl_setopt_array($ch, [
    CURLOPT_URL => $csv_url,
    CURLOPT_HEADER => false,
    CURLOPT_RETURNTRANSFER => true,
]);
$response = curl_exec($ch);

// エラーなら、適当にエラーメッセージ出して終了
if ($response === false) {
	header('Content-Type: application/json; charset=utf-8', true, 500);
    echo json_encode(['error' => 'Curl error: ' . curl_error($ch)]);
    exit;
}

/*
 * SJISのCSVをUTF-8として処理する
 */
$buffer = mb_convert_encoding($response, 'UTF-8', 'sjis-win');
$fp = tmpfile();
fwrite($fp, $buffer);
rewind($fp);

$line_number = 0;
$data = [];
while (($row = fgetcsv($fp, 0)) !== FALSE) {
    $line_number++;
	if ($line_number <= 2) {
		// 1行目、2行目はスキップ
		continue;
	} elseif (empty(array_filter($row))) {
		// 空行ならループを終了
	    break;
	}
	
	for ($index = 0; $index < count($row); $index += 2) {
		$data[] = [
		    'date' => date_format(new DateTime($row[$index + 1]), DATE_ATOM),
		    'name' => $row[$index],
	    ];
	}
}
fclose($fp);

array_multisort(array_column($data, 'date'), SORT_ASC, $data);

header('Content-Type: application/json; charset=utf-8');
echo json_encode($data);

出力結果

[
 {
  date: "2016-01-01T00:00:00+09:00",
  name: "元日"
 },
 {
  date: "2016-01-11T00:00:00+09:00",
  name: "成人の日"
 },
~中略~
 {
  date: "2018-11-23T00:00:00+09:00",
  name: "勤労感謝の日"
 },
 {
  date: "2018-12-23T00:00:00+09:00",
  name: "天皇誕生日"
 }
]

WebAPI的な使い方は想定されていないはずなので、CSVファイルはローカルにダウンロードして処理しようね!
まあ、GoogleカレンダーAPIでおk

よろしくご査収ください

7
5
0

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
7
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?