LoginSignup
4
8

More than 5 years have passed since last update.

[PHP]郵便番号APIで住所を表示

Last updated at Posted at 2019-01-08

※編集中ですが、コードだけでも共有しておきます。

今回のコード

<?php
$postalCode = 1000001; //ここに好きな郵便番号を代入
$url = 'http://zipcloud.ibsnet.co.jp/api/search?zipcode=' . $postalCode; //下7桁が任意の郵便番号になったurlを$urlに代入

//urlからはファイルが返される

$resJson = file_get_contents($url); //ファイルの内容を文字列に読み込む
$resJson = mb_convert_encoding($resJson, 'UTF8', 'ASCII,JIS,UTF-8,EUC-JP,SJIS-WIN'); //文字化け防止
$res = json_decode($resJson,true); //第二引数を「true」にすると配列型に変換

//返ってきた文字列を、それぞれの変数に代入して整理していく
$prefecture = $res['results'][0]['address1'];
$city = $res['results'][0]['address2'];
$city2 = $res['results'][0]['address3'];
$zipcode = $res['results'][0]['zipcode'];

//出力
echo '郵便番号「' . $zipcode . '」は';
echo '<br>';
echo $prefecture . $city . $city2 . 'です。';
実行結果
郵便番号「1000001」は
東京都千代田区千代田です。
4
8
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
4
8