LoginSignup
17
15

More than 5 years have passed since last update.

ホットペッパーAPIからレストラン検索するサンプル

Last updated at Posted at 2016-08-04

某QAサイトで一部の方に大人気な質問者がw
なんか、よくわからん理由で HotPepper APIに乗り換えたらしいので。

図らずも「ぐるなびAPI」「ホットペッパーAPI」に詳しくなってきましたwww
とはいえ、API使ってサイトを作るなんて、何も面白くないですね。
人の褌で相撲を取るという感じが、性に合わない…。

20150226_pepper.png

ついてに、pagination もくっつけました。
ぐるなびの場合は、そのままページ数を投げればいいのに、HotPepperの場合は開始レコードを投げるんですね…
ちょっと変わった実装。

今回も、高校数学の等差数列を思い出しながら実装。

index.php
<?php
/**
 * index.php
 *
 * @since 2016/08/04
 */
require_once './Hpepper.class.php';

/**
 * エスケープ
 * @param string $string
 * @return string
 */
function h($string)
{
    return htmlspecialchars($string, ENT_QUOTES, 'utf-8');
}

// 都道府県取得
$prefs = Hpepper::getPref();

// レストラン検索
$restaurants = Hpepper::getRestaurants();
?>
<!DOCTYPE HTML>
<html lang="ja">
    <head>
        <meta charset="UTF-8">
        <title>ホットペッパーAPIテスト(アホでも設置するだけで動く)</title>
        <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
    </head>
    <body>

        <div class="container">

            <h1>ホットペッパーAPIサンプル</h1>

            <div class="row">
                <div class="col-md-6">
                    <form method="get">
                        <div class="form-group">
                            <label for="service_area">都道府県</label>
                            <select class="form-control" name="service_area" id="service_area">
                                <option value="">都道府県</option>
                                <?php foreach ($prefs->results->service_area as $pref) : ?>
                                    <?php if ($pref->code == filter_input(INPUT_GET, 'service_area')): ?>
                                        <option value="<?= h($pref->code); ?>" selected="selected">
                                            <?= h($pref->name); ?>
                                        </option>
                                    <?php else: ?>
                                        <option value="<?= h($pref->code); ?>">
                                            <?= h($pref->name); ?>
                                        </option>
                                    <?php endif; ?>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="form-group">
                            <label for="name_kana">店名 or ふりがな</label>
                            <input class="form-control" type="text" name="name_kana" id="name_kana" value="<?= h(filter_input(INPUT_GET, 'name_kana')); ?>" />
                        </div>
                        <div class="form-group">
                            <label for="keyword">フリーワード</label>
                            <input class="form-control" type="text" name="keyword" id="keyword" value="<?= h(filter_input(INPUT_GET, 'keyword')); ?>" />
                        </div>
                        <div class="form-group">
                            <button type="submit" class="btn btn-primary">検索</button>
                        </div>
                    </form>
                </div>
            </div>
            <?php if (isset($restaurants->results)): ?>
                <?php if (isset($restaurants->results->error)): ?>
                    <div>
                        <?php foreach ($restaurants->results->error as $err) : ?>
                            <h2><?= $err->code; ?></h2>
                            <p><?= $err->message; ?></p>
                        <?php endforeach; ?>
                    </div>
                <?php else: ?>
                    <table class="table table-condensed">
                        <thead>
                            <tr>
                                <th>id</th>
                                <th>name</th>
                                <th>category</th>
                                <th>address</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($restaurants->results->shop as $rest) : ?>
                                <tr>
                                    <td><?= h($rest->id); ?></td>
                                    <td>
                                        <a href="<?= h($rest->urls->pc); ?>"><?= h($rest->name); ?></a>
                                    </td>
                                    <td><?= h($rest->genre->name); ?></td>
                                    <td><?= h($rest->address); ?></td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>

                    <ul class="pagination pagination-sm no-margin">
                        <?= Hpepper::pagination($restaurants->results->results_available); ?>
                    </ul>
                <?php endif; ?>
            <?php endif; ?>
        </div>
    </body>
</html>
Hpepper.class.php
<?php

/**
 * Hpepper.class.php
 *
 * @since 2016/08/04
 */
class Hpepper
{

    /**
     * アクセスキー
     * @var string
     */
    private static $token = '取得済みのAPIKEY';

    /**
     * 都道府県リストを取得
     * @return object
     */
    public static function getPref()
    {
        $uri = "https://webservice.recruit.co.jp/hotpepper/service_area/v1/";
        $acckey = self::$token;
        $format = "json";

        $url = sprintf("%s?format=%s&key=%s", $uri, $format, $acckey);
        $json = @file_get_contents($url);
        $obj = json_decode($json);
        return $obj;
    }

    /**
     * レストラン検索
     * @return object
     */
    public static function getRestaurants()
    {
        $uri = "http://webservice.recruit.co.jp/hotpepper/gourmet/v1/";
        $acckey = self::$token;
        $format = "json";

        $get = array(
            'format' => $format
            , 'key' => $acckey
            , 'count' => 10
            , 'name_any' => ''
        );
        if (!is_null(filter_input_array(INPUT_GET))) {
            $get += filter_input_array(INPUT_GET);
        }
        $url = sprintf("%s?%s", $uri, http_build_query($get));

        $json = @file_get_contents($url);
        $obj = json_decode($json);
        return $obj;
    }

    public static function pagination($total = 0)
    {
        $start = filter_input(INPUT_GET, 'start');
        if ($start == 0) {
            $start = 1;
        }

        if ($total == 0) {
            return;
        }

        $html = '<li%s><a href="?%s">%s</a></li>';

        //現在の頁
        $curPage = ceil($start / 10);
        $iStart = (0 < $curPage - 3) ? $curPage - 3 : 1;

        $pages = ceil($total / 10);
        $iMax = ($iStart + 6 > $pages) ? $pages : $iStart + 6;

        $arr = array();
        $params = filter_input_array(INPUT_GET);

        for ($i = $iStart; $i <= $iMax; $i++) {
            $params['start'] = ($i - 1) * 10 + 1;

            $class = ($params['start'] == $start) ? ' class="active"' : '';

            $query = http_build_query($params, '', '&amp;');
            $arr[] = sprintf($html, $class, $query, $i);
        }

        return implode(PHP_EOL, $arr);
    }

}
17
15
5

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
17
15