質問編集履歴

2

訂正します。

2016/06/13 03:37

投稿

442ky119
442ky119

スコア207

test CHANGED
File without changes
test CHANGED
@@ -1,6 +1,8 @@
1
1
  グルナビのレストラン検索APIにはリクエスト時に指定可能なパラメータの中に「市町村コード」がないらしいですが、例えば東北だけののレストランの情報を知りたい場合はどうすればいいですか?
2
2
 
3
3
 
4
+
5
+ ```PHP
4
6
 
5
7
  <?php
6
8
 
@@ -113,3 +115,5 @@
113
115
  </table>
114
116
 
115
117
  <?php endforeach; ?>
118
+
119
+ ```

1

コードを提示します。

2016/06/13 03:37

投稿

442ky119
442ky119

スコア207

test CHANGED
File without changes
test CHANGED
@@ -1 +1,115 @@
1
1
  グルナビのレストラン検索APIにはリクエスト時に指定可能なパラメータの中に「市町村コード」がないらしいですが、例えば東北だけののレストランの情報を知りたい場合はどうすればいいですか?
2
+
3
+
4
+
5
+ <?php
6
+
7
+
8
+
9
+ /**
10
+
11
+ * HTMLにテキストを出力する際は必ずこの関数を通す
12
+
13
+ */
14
+
15
+ function h($str)
16
+
17
+ {
18
+
19
+ return htmlspecialchars($str, ENT_QUOTES, 'UTF-8');
20
+
21
+ }
22
+
23
+
24
+
25
+ // エンドポイントとパラメータを定義
26
+
27
+ $endpoint = 'http://api.gnavi.co.jp/RestSearchAPI/20150630/';
28
+
29
+ $params = [
30
+
31
+ 'keyid' => '私のid',
32
+
33
+ 'format' => 'json',
34
+
35
+ 'pref' => '04',
36
+
37
+ ];
38
+
39
+
40
+
41
+ // リクエスト実行
42
+
43
+ $ch = curl_init();
44
+
45
+ curl_setopt_array($ch, [
46
+
47
+ CURLOPT_URL => $endpoint . '?' . http_build_query($params, '', '&'),
48
+
49
+ CURLOPT_RETURNTRANSFER => true, // レスポンスボディを返り値として取得
50
+
51
+ CURLOPT_FAILONERROR => true, // HTTPステータス400以上はエラーと見なす
52
+
53
+ CURLOPT_ENCODING => 'gzip', // 通信を圧縮する
54
+
55
+ ]);
56
+
57
+ $response = curl_exec($ch);
58
+
59
+
60
+
61
+ // エラーのときはテキストとしてエラーメッセージを出して終了
62
+
63
+ if ($response === false) {
64
+
65
+ header('Content-Type: text/plain; charset=UTF-8', true, 500);
66
+
67
+ exit(curl_error($ch));
68
+
69
+ }
70
+
71
+
72
+
73
+ // API側がクソ実装してなければこのjson_decodeは必ず成功するはず
74
+
75
+ $obj = json_decode($response);
76
+
77
+
78
+
79
+ // HTMLとして表示
80
+
81
+ header('Content-Type: text/html; charset=UTF-8');
82
+
83
+
84
+
85
+ ?>
86
+
87
+ <!DOCTYPE html>
88
+
89
+ <title>Example</title>
90
+
91
+ <?php foreach ($obj->rest as $r): ?>
92
+
93
+ <table border="1">
94
+
95
+ <caption><?=h($r->name)?></caption>
96
+
97
+ <tr>
98
+
99
+ <th>店舗名</th>
100
+
101
+ <td><?=h($r->name)?></td>
102
+
103
+ </tr>
104
+
105
+ <tr>
106
+
107
+ <th>アクセス</th>
108
+
109
+ <td><?=h($r->access->line)?>・<?=h($r->access->station)?>から<?=h($r->access->walk)?>分</td>
110
+
111
+ </tr>
112
+
113
+ </table>
114
+
115
+ <?php endforeach; ?>