知恵袋サンプルコード
質問検索(php)
使用API | |
---|---|
構成環境 | Apache + PHP-5.2 ・以下のライブラリが動作する環境が必要となります。 - SimpleXML - cURL |
知恵袋質問検索APIを利用し、キーワードによるQ&A(質問)検索を行うためのサンプル。
ダウンロード
サンプルご利用の際は、利用規約をご覧ください。利用規約は、ダウンロードパッケージ内のLICENSE.txtファイルに記載されています。

コード解説
ダウンロードしたアーカイブファイルを展開すると下記のようになります。
`-- sample1 |-- LICENSE.txt |-- README.txt `-- yjchiesearch.php
yjchiesearch.php
<?php /** * Yahoo! JAPAN Web APIのご利用には、アプリケーションIDの登録が必要です。 * あなたが登録したアプリケーションIDを $appid に設定してお使いください。 * アプリケーションIDの登録URLは、こちらです↓ * http://e.developer.yahoo.co.jp/webservices/register_application */ $appid = '<あなたのアプリケーションID>'; // <-- ここにあなたのアプリケーションIDを設定してください。 $CHIE_SEARCH_API_HOST = 'chiebukuro.yahooapis.jp'; $CHIE_SEARCH_API_URL = '/Chiebukuro/V1/questionSearch'; $CHIE_SEARCH_API_APPID = $appid; function escapestring($str) { return htmlspecialchars($str, ENT_QUOTES); } print<<<EOM <html> <head> <meta http-equiv="Content-Type" content="text/html" charset="utf-8"> <title>知恵袋デモサイト - 質問検索(php)</title> </head> <body> <h1>知恵袋デモサイト - 質問検索(php)</h1> EOM; print '<form action="./'. basename($_SERVER['SCRIPT_NAME']) .'">'; print '<input type="text" name="query" value="' . escapestring($_GET['query']) . '">'; print '<input type="submit" value="search">'; print '</form>'; $responseXML = ''; { $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, "http://${CHIE_SEARCH_API_HOST}${CHIE_SEARCH_API_URL}?appid=${CHIE_SEARCH_API_APPID}&query=".urlencode($_GET['query'])); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); $responseXML = curl_exec($curl); curl_close($curl); } { $xmlObj = simplexml_load_string($responseXML); foreach($xmlObj->{'Result'}->{'Question'} as $que) { print("<li>{$que->{'Content'}}<br><a href=\"{$que->{'Url'}}\">{$que->{'Url'}}</a>\n"); } } print<<<EOM <hr /> <!-- Begin Yahoo! JAPAN Web Services Attribution Snippet --> <a href="http://developer.yahoo.co.jp/about"> <img src="http://i.yimg.jp/images/yjdn/yjdn_attbtn2_105_17.gif" width="105" height="17" title="Webサービス by Yahoo! JAPAN" alt="Webサービス by Yahoo! JAPAN" border="0" style="margin:15px 15px 15px 15px"></a> <!-- End Yahoo! JAPAN Web Services Attribution Snippet --> </body> </html> EOM; ?>