【群聊问题】如何调用维基百科的API?

请参见以下 代码:


需要说明的是:这个代码如果直接用XAMPP这种本地的环境打开运行不了,因为维基百科对调用来源有限制,需要“知根知底”,所以我传到了我自己的服务器上。


<form name="input" action="" method="POST">
Wiki Query: <input type="text" name="query">
<input type="submit" value="Seach">
</form>

<?php

$user_agent = "CodeSlator/1.0 (https://github.com/hanlintao; pku***@gmail.com)";

//判断表单是否接受到数据,如果没有接收到默认检索值是China
if(isset($_POST["query"]))
{
$text = $_POST["query"];
}
else
{
$text = "China";
}

//对检索词进行编码
$encoded_text = urlencode($text);

//根据维基官方提供的调用方式来构建访问网址
$wiki_url = "https://en.wikipedia.org//w/api.php?action=query&format=json&prop=revisions&titles=".$encoded_text."&formatversion=2&rvprop=content&rvslots=*";

//使用PHP的cURL函数来访问上面的网址
$wiki_call = curl_init($wiki_url);

curl_setopt($wiki_call, CURLOPT_RETURNTRANSFER, true);
curl_setopt($wiki_call, CURLOPT_USERAGENT, $user_agent);

$wiki_response = curl_exec($wiki_call);

//判断是否收到访问结果
if($wiki_response === FALSE ){
$message_text = " There was a problem reaching Wikipedia. This might be helpful: The cURL error is " . curl_error($wiki_call);
} else {
$message_text = "WikiWiki!";
}

//停止访问网址
curl_close($wiki_call);

//将维基返回的结果转换为数组
$output = json_decode($wiki_response,true);

//把访问结果数组显示出来,在浏览器中查看网页源代码可以看得更清楚
print_r($output);

?>



已邀请:

韩林涛 - 《译者编程入门指南》作者

群友继续问,那如何调用CBDB的API?


/coding/uploads/files_user1/answer/5f2b5a091ee85804125.png


答:请参加以下代码:


稍微调整以上上面的代码。

<form name="input" action="" method="POST">
CBDB Query: <input type="text" name="query">
<input type="submit" value="Seach">
</form>

<?php

//$user_agent = "CodeSlator/1.0 (https://github.com/hanlintao; pkucater@gmail.com)";

//判断表单是否接受到数据,如果没有接收到默认检索值是China
if(isset($_POST["query"]))
{
$text = $_POST["query"];
}
else
{
$text = "王安石";
}

//对检索词进行编码
$encoded_text = urlencode($text);

//根据维基官方提供的调用方式来构建访问网址
$wiki_url = "https://cbdb.fas.harvard.edu/cbdbapi/person.php?name=".$encoded_text."&o=json";

//使用PHP的cURL函数来访问上面的网址
$wiki_call = curl_init($wiki_url);

curl_setopt($wiki_call, CURLOPT_RETURNTRANSFER, true);
//curl_setopt($wiki_call, CURLOPT_USERAGENT, $user_agent);

$wiki_response = curl_exec($wiki_call);

//判断是否收到访问结果
if($wiki_response === FALSE ){
$message_text = " There was a problem reaching Wikipedia. This might be helpful: The cURL error is " . curl_error($wiki_call);
} else {
$message_text = "WikiWiki!";
}

//echo $message_text;

//停止访问网址
curl_close($wiki_call);

//var_dump($wiki_response);

//将维基返回的结果转换为数组
$output = json_decode($wiki_response,true);

//把访问结果数组显示出来,在浏览器中查看网页源代码可以看得更清楚
print_r($output);

?>


要回复问题请先登录注册