【问题标题】:Coinmarketcap PHP API no data returnedCoinmarketcap PHP API 没有返回数据
【发布时间】:2021-10-29 07:56:16
【问题描述】:

通过 API 获取一些数据的简单测试不起作用。我使用他们自己网站上的 PHP 示例,但没有打印结果。来源:https://pro.coinmarketcap.com/api/v1#section/Quick-Start-Guide 有什么我做错了吗?我使用带有演示 API 密钥的沙盒环境。 Curl 安装在我的服务器上。非常感谢!

<?php
$url = 'https://sandbox-api.coinmarketcap.com/v1/cryptocurrency/listings/latest';
$parameters = [
  'start' => '1',
  'limit' => '5000',
  'convert' => 'USD'
];

$headers = [
  'Accepts: application/json',
  'X-CMC_PRO_API_KEY: b54bcf4d-1bca-4e8e-9a24-22ff2c3d462c'
];
$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
?>

【问题讨论】:

  • 在尝试将其解码为 JSON 之前,您是否检查过 $response 实际包含的内容...?
  • 你是对的。当我回显 $response 时,我得到“错误代码 1020”。

标签: php json coinmarketcap


【解决方案1】:

当我var_dump($response) 我得到:

error code: 1020

这是由 API 检测到机器人/脚本引起的。


考虑添加用户代理:
PHP cURL how to add the User Agent value OR overcome the Servers blocking cURL requests?

curl_setopt_array($curl, array(
    CURLOPT_URL => $request,
    CURLOPT_HTTPHEADER => $headers,
    CURLOPT_RETURNTRANSFER => 1,
    CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 6.2; WOW64; rv:17.0) Gecko/20100101 Firefox/17.0'
));

现在,脚本输出:

stdClass Object
(
    [status] => stdClass Object
        (
            [timestamp] => 2021-08-30T15:06:20.200Z
            [error_code] => 0
            [error_message] =>
            [elapsed] => 0
            [credit_count] => 1
            [notice] =>
        )

    [data] => Array
        ... and a lot more ...

【讨论】:

  • 非常感谢,帮了大忙!如果他们在他们的文档中提出这个建议应该很好。
  • 有趣的是,这个脚本已经运行了一年多,直到今天。它在早上 7 点运行没有问题,然后决定不再工作。这特工的东西修好了。谢谢!
  • 好的。它确实有效。非常感谢,但我得说他们 99.99% 的客户都是机器人和脚本。
  • 仅供参考这是一个刚刚弹出的全新错误。在今天之前,我的代码和示例代码运行良好。
猜你喜欢
  • 2017-12-31
  • 2020-07-02
  • 2021-12-19
  • 2021-12-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多