Cur*_*tis 2 php file-get-contents wikipedia-api
我可能不应该使用file_get_contents()我应该使用什么?我想保持简单.
警告: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禁止
Dav*_*dom 13
您遇到的问题与MW API的用户代理策略有关 - 您必须提供User-Agent标头,该标头必须提供一些联系方式.
您可以file_get_contents()使用流上下文执行此操作:
$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));
Run Code Online (Sandbox Code Playgroud)
话虽如此,使用cURL可能被认为更"标准" ,这肯定会给你更多的控制权:
$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);
Run Code Online (Sandbox Code Playgroud)