LoginSignup
0
0

ウィキペディアのAPIを取得するPHP雛形

Posted at

ウィキペディアのAPIを取得するPHP雛形です.

ご自由にコピペ可変してお使いいただければと思っています.
なお、制作するに当たって下記を参考にしています.

classWikipediaApi.php
<?php
class WikipediaApi
{

    private $endPoint = 'http://ja.wikipedia.org/w/api.php?';

    /**
     * @param  string $title
     * @return mixed
     */
    public function getWikipedia($title = null): mixed
    {
        try {
            if (is_null($title)) return json_encode(['error' => '記事タイトルを入力してください'], JSON_UNESCAPED_UNICODE);
            $param = [
                'format' => 'json',
                'action' => 'query',
                'prop' => 'revisions',
                'titles' => $title,
                'rvprop' => 'content',
            ];   
            $responseData = file_get_contents($this->endPoint . http_build_query($param));
        } catch (\Throwable $th) {
            //throw $th;
            return json_encode(['error' => $th->getMessage()], JSON_UNESCAPED_UNICODE);
        }

        return json_decode($responseData, false);
    }
}
//php classWikipediaApi.php '夏目漱石'
if ($title = $argv[1]) {
    var_dump((new WikipediaApi)->getWikipedia($title));
} else {
    print('処理が実行されませんでした');
}

コマンドラインより実行できます.可変すればPOSTやGETでも...出来ます.
ソースコードを理解できない方の質問は受け付けていません、ごめんなさい🙏

コマンド実行例
php classWikipediaApi.php '夏目漱石'
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