ホットペッパーAPIをPHPで
やろうと思ったのでライブラリ探してみた。
- Services_Hotpepper - 過去と他人はかえられないが、未来と自分はかえられる
- ホットペッパーWebサービスはリクルートWebサービスに統合されているため、このままでは使えない。
- Services_Recruitを公開します - よくきたblog
- 使えるがPHP4/5兼用になっているため見送り。
しょんぼりしたので、自分で作ることにする。curlで通信simplexmlでパースするもの。JSONPでも叩けるからJavascriptでもいんだけども。練習がてら頑張る。
出来た
<?php /** * HotpepperAPIを操作するクラス * * @version 0.1.0 */ class Hotpepper { /** * URL */ const BASEURL = 'http://webservice.recruit.co.jp/hotpepper/'; /** * APIキー * * @var string $apiKey */ private $apiKey; /** * APIバージョン * * @var string $apiVersion */ private $apiVersion; /** * コンストラクタ * * @param string $apiKey * @param string $apiVersion */ public function __construct($apiKey = null, $apiVersion = null) { if (is_null($apiKey)) { exit ('$apiKey not found'); } $this->apiKey = $apiKey; $apiVersion !== null ? $this->apiVersion = $apiVersion : $this->apiVersion = 'v1'; } /** * URLに接続します * * @param string $method * @param array $params * @param string $format * @return string|array|object */ private function send($method, $params = array(), $format = null) { $url = sprintf('%s%s/%s/?key=%s&%s', self::BASEURL, $method, $this->apiVersion, $this->apiKey, $this->buildQuery($params, $format)); if (!extension_loaded('curl')) { exit ('cURL extension not loaded.'); } $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); // 接続URLを定義 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // curl_execで戻り値を取得 curl_setopt($ch, CURLOPT_VERBOSE, 0); // 詳細出力をoff curl_setopt($ch, CURLOPT_HEADER, 0); // ヘッダは出さない curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5); // タイムアウトは5秒 $response = curl_exec($ch); if ($response === false) { exit ('errorno:'. curl_errno($ch) . ' error:' . curl_error($ch)); } if (curl_getinfo($ch, CURLINFO_HTTP_CODE) !== 200) { exit ('status code:' . curl_getinfo($ch, CURLINFO_HTTP_CODE)); } return simplexml_load_string($response); } /** * クエリーストリングを作成します * * @param array $params * @param string $format * @return string */ private function buildQuery($params = array(), $format = null) { if (!is_null($format)) { $params['format'] = $format; } $queries = array(); foreach ($params as $key => $value) { if(!is_null($value)) { $queries[] = $key . '=' . urlencode($value); } } return implode('&', $queries); } }