次のコードは、ウィキペディアのページから最初の段落を取得します。
<?
// action=parse: get parsed text
// page=Baseball: from the page Baseball
// format=json: in json format
// prop=text: send the text content of the article
// section=0: top content of the page
$find = $_GET['find'];
$url = 'http://en.wikipedia.org/w/api.php?action=parse&page=baseball&format=json&prop=text§ion=0';
$ch = curl_init($url);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_USERAGENT, "TestScript"); // required by wikipedia.org server; use YOUR user agent with YOUR contact information. (otherwise your IP might get blocked)
$c = curl_exec($ch);
$json = json_decode($c);
$content = $json->{'parse'}->{'text'}->{'*'}; // get the main text content of the query (it's parsed HTML)
// pattern for first match of a paragraph
$pattern = '#<p>(.*?)</p>#s'; // http://www.phpbuilder.com/board/showthread.php?t=10352690
if(preg_match_all($pattern, $content, $matches))
{
// print $matches[0]; // content of the first paragraph (including wrapping <p> tag)
echo "Wikipedia:<br>";
print strip_tags(implode("\n\n",$matches[1])); // Content of the first paragraph without the HTML tags.
}
?>
問題は、タイトルを PHP の変数にして、情報を「検索」できるようにしたい場合があることですが、クエリが常に正規の Wikipedia ページになるとは限りません。
たとえば、上記のコードで野球を検索すると、野球のページが表示されます。しかし、「マンダリン」を検索すると、次のように表示されます。
Mandarin may refer to any of the following:
しかし、オプションは表示されません。
私の質問は、ページが存在するかどうかを確認する方法はありますか?そうでない場合は、ウィキペディアからその可能性のあるオプションのリストを取得し、表示する最初のページを選択する方法はありますか?