Skip to content

Instantly share code, notes, and snippets.

@panakuma
Last active July 11, 2018 00:09
Show Gist options
  • Save panakuma/50aa8ffa24b01a2f54f7be2d5efd343c to your computer and use it in GitHub Desktop.
Save panakuma/50aa8ffa24b01a2f54f7be2d5efd343c to your computer and use it in GitHub Desktop.
<?php
echo("郵便番号をハイフン無しで入力して下さい: ");
$zipcode = trim(fgets(STDIN));
try{
if(preg_match('|^[0-9]{7}|', $zipcode)){ //入力データの簡易バリデータ(数字7桁)
$apiURL = "http://zipcloud.ibsnet.co.jp/api/search?zipcode=$zipcode";
$data = json_decode(file_get_contents($apiURL));
if($data->results === null){
throw new exception("データがありませんでした: $zipcode"); //レスポンスのresultsの中にデータがなかった場合例外を吐く
}
echo($data->results[0]->address1 . $data->results[0]->address2 . $data->results[0]->address3 . "\n");
}else{
throw new Exception("入力形式異常: $zipcode"); //入力データバリデータを通らなかった場合例外を吐く
}
}catch(Exception $e){
echo("エラーが発生しました: " . $e->getMessage() . "\n"); //例外の表示
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment