phpjsonapicoinmarketcap

Coinmarketcap API Call with PHP


I tried my first API call but something is still wrong. I added my API-Key, choose the symbol and tried to echo the price. But it is still not valid. But my echo is still 0. Maybe someone show me what i did wrong. Thank you!

    <?php

$coinfeed_coingecko_json = file_get_contents('https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest?symbol=ETH');
$parameters = [
  'start' => '1',
  'limit' => '2000',
  'convert' => 'USD'
];

$headers = [
  'Accepts: application/json',
  'X-CMC_PRO_API_KEY: XXX'
];

$qs = http_build_query($parameters); // query string encode the parameters
$request = "{$url}?{$qs}"; // create the request URL

$curl = curl_init(); // Get cURL resource
// Set cURL options
curl_setopt_array($curl, array(
  CURLOPT_URL => $request,            // set the request URL
  CURLOPT_HTTPHEADER => $headers,     // set the headers 
  CURLOPT_RETURNTRANSFER => 1         // ask for raw response instead of bool
));

$response = curl_exec($curl); // Send the request, save the response
print_r(json_decode($response)); // print json decoded response
curl_close($curl); // Close request

$coinfeed_json = json_decode($coinfeed_coingecko_json, false);

$coinfeedprice_current_price = $coinfeed_json->data->{'1'}->quote->USD->price;


?>
 <?php  echo $coinfeedde = number_format($coinfeedprice_current_price, 2, '.', '');  ?>

API Doc: https://coinmarketcap.com/api/v1/#operation/getV1CryptocurrencyListingsLatest


Solution

  • There is a lot going on in your code.

    I have changed a few things to make it work:

    $url = "https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest";
    
    $headers = [
      'Accepts: application/json',
      'X-CMC_PRO_API_KEY: ___YOUR_API_KEY_HERE___'
    ];
    
    $request = "{$url}"; // create the request URL
    
    $curl = curl_init(); // Get cURL resource
    // Set cURL options
    curl_setopt_array($curl, array(
      CURLOPT_URL => $request,            // set the request URL
      CURLOPT_HTTPHEADER => $headers,     // set the headers 
      CURLOPT_RETURNTRANSFER => 1         // ask for raw response instead of bool
    ));
    
    $response = curl_exec($curl); // Send the request, save the response
    $json = json_decode($response);
    curl_close($curl); // Close request
    
    var_dump($json->data[0]->quote->USD->price);
    var_dump($json->data[1]->quote->USD->price);