从维基百科文章解析第一段?

时间:2012-06-09 12:20:38

标签: php xml wikipedia-api

  

可能重复:
  Getting content using wikipedia API
  Using PHP, how do I get the first paragraph of a Wikipedia article with the MediaWiki API?

这主要是与XML相关的问题。

我正在尝试使用MediaWiki API执行此操作。

我设法以XML格式获得响应(如果更容易,可以更改为JSON),并且我在响应中看到了我需要的所有内容。例如:

http://en.wikipedia.org/w/api.php?format=xml&action=query&titles=War%20and%20Peace&prop=revisions&rvprop=content&format=xmlfm

我在这里使用xmlfm是出于格式化的原因。在PHP中我正在做:

$request = "http://en.wikipedia.org/w/api.php?format=xml&action=query&titles=War%20and%20Peace&prop=revisions&rvprop=content&format=xml";

$response = @file_get_contents($request);

$wxml = simplexml_load_string($response);

var_dump($wxml);

打印出XML中的所有内容。我的问题是,如何从中得到第一段?

我可以从完整的文章中解析它,所以基本上我要问的是,如何从这个XML中获取文章文本?当然,如果有办法直接找到第一段,那将是最好的。

1 个答案:

答案 0 :(得分:5)

我肯定会说你正在寻找this

如果要检索第一部分中的所有内容(而不仅仅是第一段):

// 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

$url = 'http://en.wikipedia.org/w/api.php?action=parse&page=Baseball&format=json&prop=text&section=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)
    print strip_tags(implode("\n\n",$matches[1])); // Content of the first paragraph without the HTML tags.
}
相关问题