LoginSignup
18
24

More than 5 years have passed since last update.

ぐるなびAPIからレストラン検索するサンプル

Last updated at Posted at 2016-08-03

某QAサイトで一部の方に大人気な質問者がw

その回答の時に作ったサンプルコードにエラー時のメッセージを表示する機能を足してみた。

index.php
<?php
/**
 * index.php
 *
 * @since 2016/08/01
 */
require_once './global_functions.php';
require_once './Gnavi.class.php';

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

// レストラン検索
$restaurants = Gnavi::getRestaurants();
?>
<!DOCTYPE HTML>
<html lang="ja">
    <head>
        <meta charset="UTF-8">
        <title>ぐるなびAPIテスト(アホでも設置するだけで動く)</title>
    </head>
    <body>
        <form action="" method="get">
            <p>
                <label for="pref">都道府県</label>
                <select name="pref" id="pref">
                    <option value="">都道府県</option>
                    <?php foreach ($prefs->pref as $pref) : ?>
                        <?php if ($pref->pref_code == filter_input(INPUT_GET, 'pref')): ?>
                            <option value="<?= h($pref->pref_code); ?>" selected="selected">
                                <?= h($pref->pref_name); ?>
                            </option>
                        <?php else: ?>
                            <option value="<?= h($pref->pref_code); ?>">
                                <?= h($pref->pref_name); ?>
                            </option>
                        <?php endif; ?>
                    <?php endforeach; ?>
                </select>
            </p>
            <p>
                <label for="freeword">フリーワード</label>
                <input type="text" name="freeword" id="freeword" value="<?= h(filter_input(INPUT_GET, 'freeword')); ?>" />
            </p>
            <p>
                <button type="submit">検索</button>
            </p>
        </form>

        <div>
            <?php if (isset($restaurants->error)): ?>
                <div>
                    <h2><?= $restaurants->error->code; ?></h2>
                    <p><?= $restaurants->error->message; ?></p>
                </div>
            <?php else: ?>
                <table>
                    <thead>
                        <tr>
                            <th>id</th>
                            <th>name</th>
                            <th>category</th>
                            <th>address</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($restaurants->rest as $rest) : ?>
                            <tr>
                                <td><?= h($rest->id); ?></td>
                                <td>
                                    <a href="<?= h($rest->url); ?>"><?= h($rest->name); ?></a>
                                </td>
                                <td><?= h($rest->category); ?></td>
                                <td><?= h($rest->address); ?></td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>

                <div class="pagination">
                    <?= pagination($restaurants->page_offset, $restaurants->total_hit_count); ?>
                </div>

            <?php endif; ?>
        </div>
    </body>
</html>
global_functions.php
<?php

/**
 * global_functions.php
 *
 * @since 2016/08/01
 */

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

/**
 * ページネーション
 * @param int $page
 * @param int $total
 * @return string
 */
function pagination($page, $total)
{
    $delta = 3;
    if ($total < 1) {
        return;
    }
    $query = (is_array(filter_input_array(INPUT_GET))) ?
        filter_input_array(INPUT_GET) : [];
    if (isset($query['offset_page'])) {
        unset($query['offset_page']);
    }
    $querystring = http_build_query($query);
    $limit = 10;
    $placeholder = "<span%s><a href=\"?offset_page=%d&%s\">%s</a></span> ";

    // 最大ページ数
    $maxPage = ceil($total / $limit);

    $min = max([$page - $delta, 1]);
    $max = min([$page + $delta, $maxPage - 1]);

    $html = '';
    if ($page > 1) {
        $html .= sprintf($placeholder, '', 1, $querystring, '&laquo;');
        $html .= sprintf($placeholder, '', $page, $querystring, '前へ');
    }
    for ($i = $max - 6; $i < $min + 7; $i++) {
        if ($i > -1 && $i < $maxPage) {
            $html .= sprintf($placeholder
                , ($i == $page - 1) ? ' class="active"' : ''
                , $i + 1
                , $querystring
                , $i + 1
            );
        }
    }
    if ($page < $maxPage) {
        $html .= sprintf($placeholder, '', $page + 1, $querystring, '次へ');
        $html .= sprintf($placeholder, '', $maxPage, $querystring, '&raquo;');
    }
    return $html;
}
Gnavi.class.php
<?php

/**
 * Gnavi.class.php
 *
 * @since 2016/08/01
 */
class Gnavi
{

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

    /**
     * 都道府県リストを取得
     * @return object
     */
    public static function getPref()
    {
        $uri = "http://api.gnavi.co.jp/master/PrefSearchAPI/20150630/";
        $acckey = self::$token;
        $format = "json";

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

    /**
     * レストラン検索
     * @return object
     */
    public static function getRestaurants()
    {
        $uri = "http://api.gnavi.co.jp/RestSearchAPI/20150630/";
        $acckey = self::$token;
        $format = "json";

        $get = [
            'format' => $format
            , 'keyid' => $acckey
        ];
        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;
    }

}
18
24
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
18
24