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

Yahoo!キーフレーズ抽出API V1が終了してしまい、V2に移行する必要があったので、サンプルプログラムを載せておく

V1はGETでパラメータを遅れたが、V2はJSONをPOSTする必要がある

$sentence = "評価対象の文章";

$appid = '<APIキーを入力>';

$url = "https://jlp.yahooapis.jp/KeyphraseService/V2/extract";

$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" => $sentence
    )
);
$data = json_encode($data);

$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);

//$body->result->phrasesに各フレーズの要素が格納されている
//$body->result->phrases->textがフレーズ
$result_num = count($body->result->phrases);
  
if($result_num > 0){
    for($i = 0; $i < $result_num; $i++){
      $result = $body->result->phrases[$i];
      $resultStr .= mb_convert_encoding(escapestring($result->text), 'utf-8', 'auto')."、";
    }
}else{
      $resultStr = "";
}

//抽出されたフレーズを「、」区切りで表示
echo $resultStr;

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です