如何从维基百科获取不同公司的摘要?

时间:2013-03-09 17:56:23

标签: php api wikipedia

我正在尝试从维基百科获取用户输入公司的摘要段落。

例如,如果用户进入Google,我需要显示Google的摘要段落。

我目前正在使用的代码:

// action=parse: get parsed text
// page=$input
// 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=$input&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>#Us'; // http://www.phpbuilder.com/board/showthread.php?t=10352690
if(preg_match($pattern, $content, $matches))
{
    // print $matches[0]; // content of the first paragraph (including wrapping <p> tag)
    print strip_tags($matches[1]); // Content of the first paragraph without the HTML tags.
}

如果$input = "Zynga"有效,但$input = "Google"无效,因为它返回“参考:[4]。”

1 个答案:

答案 0 :(得分:0)

您可以使用action=query&prop=extracts代替exintro=选项。例如。 https://en.wikipedia.org/w/api.php?action=query&prop=extracts&format=json&exlimit=1&exintro=&explaintext=&titles=Google 对于谷歌。

这应该删除大多数不需要的格式,例如引用。