Coinmarketcap API 调用 PHP

Coinmarketcap API Call with PHP

我尝试了第一个 API 呼叫,但仍然有问题。我添加了我的 API-Key,选择符号并尝试回应价格。但它仍然无效。但我的回声仍然是 0。也许有人告诉我我做错了什么。谢谢!

    <?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 文档:https://coinmarketcap.com/api/v1/#operation/getV1CryptocurrencyListingsLatest

您的代码中发生了很多事情。

  • 首先$url没有定义
  • 其次你提出了两个请求,其中一个我已经删除了
  • 第三;您可以通过 $json->data[0]->quote->USD->price
  • 访问 json 对象
  • 第四;我删除了无效的请求参数

我更改了一些内容以使其工作:

$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);