Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...