douzhiba6873 2012-06-23 18:52
浏览 58
已采纳

如何在PHP中使用Stack Overflow API

I have the following URL:

https://api.stackexchange.com/2.0/questions?page=1&pagesize=30&order=desc&sort=activity&site=stackoverflow

When I type this URL in my browser's address bar, it gives me a JSON response, which I need in PHP. I tried using cURL to fetch it (see below code), but it didn't work — no response is printed on the page.

function get_json($url) {
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_URL, $url);

    $data = curl_exec($ch);
    $resultCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($resultCode == 200) {
        return json_decode($data);
    } else {
        return false;
    }
}

$json = get_json('https://api.stackexchange.com/2.0/questions?page=1&pagesize=30&
  key=VVq3kJHSjQ*7qgpiRaVoLA%28%28&site=stackoverflow');
echo '<pre>';
print_r($json);

How can I fetch this URL and convert it into a PHP array the right way?

  • 写回答

3条回答 默认 最新

  • drwjv28028 2012-06-23 18:59
    关注

    Last I checked, all responses from the API were gzip'd:

    $ch = curl_init();
    curl_setopt_array($ch, array(
        CURLOPT_URL => $url
      , CURLOPT_HEADER => 0
      , CURLOPT_RETURNTRANSFER => 1
      , CURLOPT_ENCODING => 'gzip'
    ));
    $data = curl_exec($ch);
    var_dump($data);
    var_dump(json_decode($data));
    

    Setting CURLOPT_ENCODING enables automatic un gzip'ing of the response, in addition to sending an Accept-Encoding: gzip in the http request, although sending that header isn't strictly required for this to work.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 人在外地出差,速帮一点点
  • ¥15 如何使用canvas在图片上进行如下的标注,以下代码不起作用,如何修改
  • ¥15 Windows 系统cmd后提示“加载用户设置时遇到错误”
  • ¥50 vue router 动态路由问题
  • ¥15 关于#.net#的问题:End Function
  • ¥15 无法import pycausal
  • ¥15 VS2022创建MVC framework提示:预安装的程序包具有对缺少的注册表值的引用
  • ¥15 weditor无法连接模拟器Local server not started, start with?
  • ¥20 6-3 String类定义
  • ¥15 嵌入式--定时器使用