LoginSignup
2
4

More than 5 years have passed since last update.

Yahooの日本語形態素解析APIからajaxを用いてデータを得るコード

Posted at

概要

この記事では、Yahoo Japanが提供している日本語形態素解析を用いて、形態素解析データを得るPHPおよびjQueryを紹介しています。

※このAPIを利用するためには、YahooにてアプリケーションIDの登録が必要です。登録はこちらから。

コード

sample.php
<?php
$appid = '<あなたのアプリケーションID>'; // <-- ここにあなたのアプリケーションIDを設定してください。
function curl($url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 60);
    $xml  = curl_exec($ch);
    curl_close($ch);
    return $xml;
}
/*
    ここから処理
 */
if (isset($_POST['sentence'])) {
    $sentence = mb_convert_encoding($_POST['sentence'], 'utf-8', 'auto');
    $results = "ma,uniq";
    $response = "surface,reading,pos,baseform,feature";

    $url = "http://jlp.yahooapis.jp/MAService/V1/parse";
    $url .= "?appid=".$appid;
    $url .= "&results=".$results;

    $url .= "&sentence=".urlencode($sentence);
    $url .= "&response=".$response;
    echo json_encode(new SimpleXMLElement(curl($url)));
}
?>
$.ajax({
    type: "POST",
    url: "sample.php",
    data: {sentence: sentence},
    success: function(data) {
        console.log(data);
    },
    error: function(XMLHttpRequest, textStatus, errorThrown) {
        console.log(XMLHttpRequest, textStatus, errorThrown);
    },
    dataType: "json"
});
2
4
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
4