1

I tried to connect Coinmarketcap's API using PHP curl to take out the live bitcoin price out of it as a practice. The point is that the output it gives is way too confusing that I have got no idea about how should I take the "price" out of it. There were some similar questions around but unfortunately, the responses didn't help me. So I was wondering how is it possible to take the price of bitcoin out of the return given by API? It seems like I'm misunderstanding arrays and objects since I'm still a newbie. This is what "die and dump" returns:

  #data: array:1 [▼
    "response" => """
      {
          "status": {
              "timestamp": "2019-04-15T14:03:35.573Z",
              "error_code": 0,
              "error_message": null,
              "elapsed": 5,
              "credit_count": 1
          },
          "data": [
              {
                  "id": 1,
                  "name": "Bitcoin",
                  "symbol": "BTC",
                  "slug": "bitcoin",
                  "circulating_supply": 17646787,
                  "total_supply": 17646787,
                  "max_supply": 21000000,
                  "date_added": "2013-04-28T00:00:00.000Z",
                  "num_market_pairs": 7253,
                  "tags": [
                      "mineable"
                  ],
                  "platform": null,
                  "cmc_rank": 1,
                  "last_updated": "2019-04-15T14:02:29.000Z",
                  "quote": {
                      "USD": {
                          "price": 5166.87433557,
                          "volume_24h": 11238888046.6075,
                          "percent_change_1h": 0.0140845,
                          "percent_change_24h": 1.39641,
                          "percent_change_7d": -0.981349,
                          "market_cap": 91178730855.57031,
                          "last_updated": "2019-04-15T14:02:29.000Z"
                      }
                  }
              }
          ]
      }
      """
  ]

Here is the code which requests from API:

   function apiGet($url)
    {
        $parameters = [
            'start' => '1',
            'limit' => '3',
        ];
        $query = http_build_query($parameters);

        $curl = curl_init();

        curl_setopt_array($curl, array(
            CURLOPT_URL => "$url",
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_TIMEOUT => 30000,
            CURLOPT_POST => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "GET",
            CURLOPT_HTTPHEADER => array(
                'Content-Type: application/json',
                'Accept-Encoding: deflate, gzip',
                'X-CMC_PRO_API_KEY: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',


            ),
        )
        );

        $response = curl_exec($curl);
        $err = curl_error($curl);
        curl_close($curl);

        if ($err) {
            echo "cURL Error #:" . $err;
        } else {
            print_r(json_decode($response));
        }
        return view('price', compact('response'));
    }

        $parameters = [
             'start' => '1',
             'limit' => '1',
         ];
         $query = http_build_query($parameters);
         $btc = new \App\Http\Controllers\CoinsController();
         $result = $btc->apiGet('https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest'."?".$query);

         dd($result);
Sina R
  • 97
  • 2
  • 9

2 Answers2

1

That's a nested key value array that contains a json string. You can get the price like this:

$price = json_decode($result['response'])->data[0]->quote->USD->price;
namelivia
  • 2,657
  • 1
  • 21
  • 24
1

Also for your knowledge. You can use the Arr::get() helper provided by Laravel. See docs:

use \Illuminate\Support\Arr;

...

$data = json_decode($result['response'], true);

$price = Arr::get($data, 'data.0.quote.USD.price');
thisiskelvin
  • 4,136
  • 1
  • 10
  • 17