【问题标题】:Parse curl response from github api解析来自 github api 的 curl 响应
【发布时间】:2014-01-21 01:46:30
【问题描述】:

我是 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,但不是我第一次进行 Web 开发(这几周我一直在为基于 Hakyll 的博客投稿)。

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

【问题讨论】:

    标签: php api curl github


    【解决方案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
    

    【讨论】:

    • 谢谢。当我使用它时没有任何反应,但我会调查它。
    • 你可以试试我发布的例子(它会在测试后工作),另外,尝试你的尝试并在问题中更新它,这样我们就可以知道你卡在哪里了。
    猜你喜欢
    • 1970-01-01
    • 2012-02-05
    • 1970-01-01
    • 2020-05-20
    • 2017-06-14
    • 1970-01-01
    • 1970-01-01
    • 2015-04-03
    • 2011-04-30
    相关资源
    最近更新 更多