LoginSignup
2
0

More than 1 year has passed since last update.

Yahoo!のキーフレーズ抽出API(v2)のPHPサンプルプログラム

Last updated at Posted at 2021-09-18

Yahooが提供するキーフレーズ抽出APIがありますが、つい最近V2にバージョンアップされました。このAPIを利用されている方も多いと思いますが、2022年1月末に廃止予定とのことで早急に移行しないとなりませんが、V1にあったPHPのサンプルプログラムがV2ではPythonのみとなっています。

いろいろ試行錯誤してサンプルプログラムを作りましたので公表します。
すでに利用している人向けのドキュメントですので「どうやったら利用できるか?」などの基本的な話はここでは取り扱いません。

ソース

<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <?php

    $appId = "your app key";
    $url = "https://jlp.yahooapis.jp/KeyphraseService/V2/extract";
    $word = "秋葉原から国立競技場に行くには末広町駅から東京メトロ銀座線に乗車して外苑前駅で降ります";

    $headers = [
        "Content-Type: application/json",
        "User-Agent: Yahoo AppID: ".$appId,
    ];

    $data = array(
        "id" => "1234-1",
        "jsonrpc" => "2.0",
        "method" => "jlp.keyphraseservice.extract",
        "params" => array(
        "q" => $word
        )
    );
    $data = json_encode($data);

    //XMLの解析
    $curl = curl_init($url);
    $options = array(
        // HEADER
        CURLOPT_HTTPHEADER => $headers,
        // Method
        CURLOPT_POST => true, // POST
        // body
        CURLOPT_POSTFIELDS => $data,
        // 変数に保存。これがないと即時出力
        CURLOPT_RETURNTRANSFER => true,
        // header出力
        CURLOPT_HEADER => true, 
    );

    //set options
    curl_setopt_array($curl, $options);
    //取得
    $response = curl_exec($curl);

    //ヘッダー取得
    $header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE); 
    //ヘッダー切り出し
    $header = substr($response, 0, $header_size);
    //BODY切り出し
    $body = substr($response, $header_size);
    //JSONに変換
    $body = json_decode($body); 

    curl_close($curl);
    print_r($body->result->phrases);

?>
</body>
</html>

リンク

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