如何使用PHP从Wikipedia API获得结果? [英] How to get results from the Wikipedia API with PHP?

查看:114
本文介绍了如何使用PHP从Wikipedia API获得结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可能不应该使用file_get_contents()我应该使用什么?我想保持简单.

I'm probably not supposed to use file_get_contents() What should I use? I'd like to keep it simple.

警告:file_get_contents(http://en.wikipedia.org/w/api.php?action=query&titles=Your_Highness&prop=revisions&rvprop=content&rvsection=0):无法打开流:HTTP请求失败! HTTP/1.0 403禁止

Warning: file_get_contents(http://en.wikipedia.org/w/api.php?action=query&titles=Your_Highness&prop=revisions&rvprop=content&rvsection=0): failed to open stream: HTTP request failed! HTTP/1.0 403 Forbidden

推荐答案

此处遇到的问题与MW API的

The problem you are running into here is related to the MW API's User-Agent policy - you must supply a User-Agent header, and that header must supply some means of contacting you.

您可以使用file_get_contents()流上下文来做到这一点:

You can do this with file_get_contents() with a stream context:

$opts = array('http' =>
  array(
    'user_agent' => 'MyBot/1.0 (http://www.mysite.com/)'
  )
);
$context = stream_context_create($opts);

$url = 'http://en.wikipedia.org/w/api.php?action=query&titles=Your_Highness&prop=revisions&rvprop=content&rvsection=0';
var_dump(file_get_contents($url, FALSE, $context));

话虽如此,使用 cURL 可能被认为是更标准"的,这将当然可以给您更多的控制权:

Having said that, it might be considered more "standard" to use cURL, and this will certainly give you more control:

$url = 'http://en.wikipedia.org/w/api.php?action=query&titles=Your_Highness&prop=revisions&rvprop=content&rvsection=0';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_USERAGENT, 'MyBot/1.0 (http://www.mysite.com/)');

$result = curl_exec($ch);

if (!$result) {
  exit('cURL Error: '.curl_error($ch));
}

var_dump($result);

这篇关于如何使用PHP从Wikipedia API获得结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆