パーサーというよりスクレイピングだと思います。
以下のスクリプトではどうでしょう
$url に解析したいWikiのURLを入力してください。
<?php mb_internal_encoding('UTF-8'); mb_regex_encoding('UTF-8'); ini_set('user_agent', 'User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)'); $url = 'http://ja.wikipedia.org/wiki/%E6%9D%B1%E4%BA%AC%E5%A4%AA%E3%83%BB%E3%82%86%E3%82%81%E5%AD%90'; $pat = "/(<p>.*<\/p>)\n<table id=\"toc\" class=\"toc\">/msiu"; $buf = file_get_contents($url); preg_match($pat, $buf, $arr); echo <<< EOD <html> <head> <meta charset="utf-8"> <body> $arr[1]; </body> </html> EOD; ?>
▽2
●
Cherenkov ●67ポイント ベストアンサー |
目的は概要の抽出。概要の条件は、
#mw-content-text > p かつ #mw-content-text > table[0] よりも前にある要素とする。
simple_html_dom.phpを使って作ってみました。utf-8で保存。
<?php function pr($var) { echo '<pre>'; print_r($var); echo '</pre>'; } header('Content-Type:text/html; charset=UTF-8'); require_once("simple_html_dom.php"); function getWikiSummary($keyword) { $result = ''; $url = 'http://ja.wikipedia.org/wiki/' . urlencode($keyword); $url = preg_replace('/%28/u', '(', $url); //括弧はこの処理をしないとダメみたい。 $url = preg_replace('/%29/u', ')', $url); $html = file_get_html($url); $ps = $html->find('#mw-content-text > p'); for ($i = 0, $n = count($ps); $i < $n; $i++) { $result .= $ps[$i]->innertext; if ($ps[$i]->nextSibling()->tag === 'table') { break; } } $html->clear(); return $result; } $keywords = array('東京太・ゆめ子', 'カナリア_(お笑い)'); echo '<dl>'; foreach ($keywords as $keyword) { $summary = getWikiSummary($keyword); echo '<dt>' . $keyword . '</dt>'; echo '<dd>' . $summary . '</dd>'; } echo '</dl>';