概要
この記事では、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"
});