LoginSignup
0
0

More than 5 years have passed since last update.

Google+のAPIを利用して特定の記事を検索する。

Posted at

下記のGoogle Libraryを利用してGoogle+の記事を検索してみるお話。
https://developers.google.com/api-client-library/php/?hl=ja
(Beta版なのが気になるところ…)

GoogleサービスのAPIキーはGoogle Developers Consoleで取得ができます。

Googleの各サービスで共通で利用できるのでClientの取得は切り分けておくと便利。

<?php namespace Lib;
/**
 * Google関連
 *
 * ライブラリ
 *   https://developers.google.com/api-client-library/php/
 */

use Google_Client;

class GoogleManager 
{

    private $__client  = null;
    private $__api_key = 'xxxxxxxxxxxxxxx';

    /**
     * client
     */
    protected function _getClient()
    {
        if (is_null($this->__client))
        {
            $this->__client = new Google_Client();
            $this->__client->setDeveloperKey($this->__api_key);
        }
        return $this->__client;
    }

}

Google+のAPIを利用するためのサービス登録などの準備

<?php namespace Lib;
/**
 * GooglePlus関連
 *
 * GooglePlus公式
 *   https://developers.google.com/+/web/api/rest/
 */

use Google_Service_Plus;
use Google_Service_Exception;

class GooglePlusManager extends GoogleManager
{

    private $__service = null;

    /**
     * GooglePlusのサービス登録
     */
    private function __getService()
    {
        if (is_null($this->__service))
        {
            $this->__service = new Google_Service_Plus($this->_getClient());
        }
        return $this->__service;
    }

    /**
     * 指定した条件でアクティビティを検索
     *  https://developers.google.com/+/web/api/rest/latest/activities/search
     */
    public function searchActivities($str, $options=[])
    {
        $plus = $this->__getService();
        try {
            return $plus->activities->search($str, $options);
        } catch (Google_Service_Exception $e) {
//          echo $e->getMessage();
            return false;
        }
    }
}

実際に利用して内容を取得してみる

    public function sample()
    {
        $res = GooglePlusManager::searchActivities("{$u}", [
            'language'   => 'ja',
            'maxResults' => 20,
            'orderBy'    => 'best',
        ]);
        if (!$res)
        {
            exit;
        }
        print_r($res['item']['content']);
        exit;
    }

GooglePlusManager::searchActivities('hoge')で記事検索ができ、
検索結果には$array['items']でアクセスできる。

0
0
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
0
0