从github api解析卷曲响应

时间:2014-01-03 11:40:01

标签: php api curl github

我是php的新手,但我现在正在努力学习。我想做什么: 像这样向github api发送curl请求:

curl_setopt($ch, CURLOPT_URL, 'https://api.github.com/legacy/repos/search/language:' . $lang);

当我收到结果显示为一个漂亮的HTML页面。我现在收到的响应显示为用github api文档http://developer.github.com/v3/search/编写的响应。

这是我第一次尝试学习PHP,但这不是我第一次进行网络开发(这几周我一直在为基于Hakyll的博客做贡献)。

我的问题是:我如何解析结果以便在html页面中很好地格式化它们?

1 个答案:

答案 0 :(得分:1)

结果通过 JSON 返回。您可以使用json_decode()

cURL $response传递给此功能。这样print_r(json_decode($response,1));

如何操作的示例

<?php
$json='{
  "text_matches": [
    {
      "object_url": "https://api.github.com/repositories/3081286",
      "object_type": "Repository",
      "property": "name",
      "fragment": "Tetris",
      "matches": [
        {
          "text": "Tetris",
          "indices": [
            0,
            6
          ]
        }
      ]
    },
    {
      "object_url": "https://api.github.com/repositories/3081286",
      "object_type": "Repository",
      "property": "description",
      "fragment": "A C implementation of Tetris using Pennsim through LC4",
      "matches": [
        {
          "text": "Tetris",
          "indices": [
            22,
            28
          ]
        }
      ]
    }
  ]
}';


$jarr=json_decode($json,1);
echo $jarr['text_matches'][0]['object_url']; //"prints" https://api.github.com/repositories/3081286