GuzzleでGET送信してデータを表示する
目次
はじめに
Guzzleというものを知ったので軽く練習
Guzzleとは?
HTTP要求の送信を簡単にし、Webサービスとの統合を簡単にするPHP HTTPクライアント
インストール
これでGuzzleが使用可能になります。
composer require guzzlehttp/guzzle
記述
xxController.php
use GuzzleHttp\Client; //追加 //web.phpにsendGetアクション記述しておく public function sendGet() { $client = new Client(['base_uri' => 'http://weather.livedoor.com/']); $methods = 'GET'; $path = 'forecast/webservice/json/v1'; $options = ['query'=>'city=400040']; $response = $client->request($methods, $path,$options); $responseBody = json_decode($response->getBody()->getContents(), true); return response()->json($responseBody); }
詳細
1,ベースとなるURIをセットしてあげる(clientは不変なオブジェクトなので変更はできない)
$client = new Client(['base_uri' => 'http://weather.livedoor.com/']);
2, 普通に記述するとこのようになる。
$response = $client->request('GET','forecast/webservice/json/v1' ,['query'=>'city=400040']);
つまり
request(HTTPメソッド,ベースURIの後に続くパス,クエリなど)
これだと長いと感じたので変数に入れています。
$methods = 'GET'; $path = 'forecast/webservice/json/v1'; $options = ['query'=>'city=400040']; $response = $client->request($methods, $path,$options);
3, デコードして画面に表示
$responseBody = json_decode($response->getBody()->getContents(), true); return response()->json($responseBody);
今回のエラー
これでURLにアクセスした結果。。。
$client = new GuzzleHttp\Client(['base_uri' => 'http://weather.livedoor.com/']); $methods = 'GET'; $path = 'forecast/webservice/json/v1'; $options = ['query'=>'city=400040']; $response = $client->request($methods, $path,$options); $responseBody = $response->getBody(); return response()->json($list);
あれ?表示されない。。。
{}
原因
json_decodeしてなかった...
$client = new GuzzleHttp\Client(['base_uri' => 'http://weather.livedoor.com/']); $methods = 'GET'; $path = 'forecast/webservice/json/v1'; $options = ['query'=>'city=400040']; $response = $client->request($methods, $path,$options); //原因(json_decodeしてなかった...) $list = json_decode($response->getBody()->getContents(), true); return response()->json($list);
取得できた!
{"pinpointLocations":[{"link":"http:\/\/weather.livedoor.com\/area\/forecast\/4020200","name":"\u5927\u725f\u7530\u5e02"},{"link":"http:{"pinpointLocations":[{"link":"http:\/\/weather.livedoor.com\/area\/forecast\/4020200","name":"\u5927\u725f\u7530\u5e02"},{"link":"http:\/\/weather.livedoor.com\/area\/forecast\/4020300","name":"\u4e45\u7559\u7c73\u5e02"}...
デコード
デコード 符号化(エンコード)されたデータを元の状態に戻す(復元、復号)すること。 そのためのソフトウェアや装置をデコーダーという。 たとえば、圧縮されたデータの解凍(復元)、暗号化されたファイルの解読(復号)、デジタル変換された音声データをD/Aコンバーターを使ってアナログ信号に戻すことなどがこれに当たる。
つまり、jsonはPHPでごニャゴにゃできないからPHPでごニャゴにゃできるように変換してあげる必要がある。
$list = json_decode($response->getBody()->getContents(), true);
これで一旦OK