dousuo8400 2012-01-21 20:19
浏览 38
已采纳

如何从PHP获取Wikipedia API的结果?

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

  • 写回答

4条回答 默认 最新

  • dongnan1899 2012-01-21 20:41
    关注

    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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分