Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
660 views
in Technique[技术] by (71.8m points)

file get contents - How to get results from the Wikipedia API with PHP?

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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));

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...