0
0

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 3 years have passed since last update.

Yahoo Web API で 郵便番号から住所を取得

Posted at

このAPIの素晴らしいところは、その住所から最寄りの駅まで取得できる。

今回は、
・curl を使って取得し
・ユーザーの町名以外の部分まで表示したいので、詳細住所はカット
・pref 東京都(県)city 銀座 エリア

に分けて取得する。

$app_id は変更して下さい。

hoge.php

//        $sentence = "1040061";//ハイフンあり、なしどちらでも結果一緒
        $sentence = "4530013";//ハイフンあり、なしどちらでも結果一緒

        $api = 'https://map.yahooapis.jp/search/zip/V1/zipCodeSearch';
        $app_id = 'xxxPUdNS3BGbmhjdE5RNCZzPWNvbnN1bWVyxxxcmV0Jng9MDc-';//Yahoo Developer の アプリケーションID

        $params = [
            'query' => $sentence,
            'detail' => 'full'//詳細住所まで取得
        ];

        $ch = curl_init($api);
        curl_setopt_array($ch,
            [
                CURLOPT_POST           => true,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_USERAGENT      => "Yahoo AppID: ".$app_id,
                CURLOPT_POSTFIELDS     => http_build_query($params),
            ]
        );

        $result = curl_exec($ch);
        $res = simplexml_load_string($result);

        curl_close($ch);


        var_dump($res);//取得したものをとりあえず、全て表示
        
        $area = [];
        foreach ($res->Feature->Property->AddressElement as $v) {
            $tmp = (array)$v->Name;//objectを配列に変換
            $tmp = array_shift($tmp);
            $area[] = $tmp;
        }

//        住所表示用に特定されないっように最後の住所(町名)をカット
        array_pop($area);
        $pref = array_shift($area);
        $area = join("",$area);




//        都道府県
        print_r($pref);

//        それ以下の住所
        print_r($area);




以上

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?