我的脚本整体运行,但API响应非常慢。
这就是我的代码:
<?php
error_reporting(E_ALL);
$config = include('config.php');
$predictions = include('predicton.php');
function fetchData($currency) {
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => 'https://api.coinmarketcap.com/v1/ticker/'.$currency.'/?convert=EUR'
));
$response = curl_exec($curl);
$response = json_decode($response, true);
curl_close($curl);
return $response;
}
function convertData($currency) {
global $config;
$response = fetchData($currency);
$id = $response[0]['id'];
$name = $response[0]['name'];
$value = $response[0]['price_eur'];
$perc_change_h = $response[0]['percent_change_1h'];
$perc_change_d = $response[0]['percent_change_24h'];
$perc_change_w = $response[0]['percent_change_7d'];
$amount = $config[$currency]['amount'];
$starting_price = $config[$currency]['starting_price'];
$spend = $amount * $starting_price;
$total = $amount * $value;
$profit = $total - $spend;
return array(
'id' => $id,
'name' => $name,
'value' => round($value, 4),
'change_hour' => $perc_change_h,
'change_day' => $perc_change_d,
'change_week' => $perc_change_w,
'amount' => $amount,
'starting' => number_format($starting_price, 4),
'spend' => number_format($spend, 2),
'total' => number_format($total, 2),
'profit' => number_format($profit, 2)
);
}
function convertPrediction ($currency, $percentage) {
global $config, $predictions;
$amount = $config[$currency]['amount'];
$prediction = $predictions[$currency]['value'];
$value = $amount * $prediction / 100 * $percentage;
$value = round($value, 2);
return $value;
}
示例api请求:https://api.coinmarketcap.com/v1/ticker/stellar/?convert=EUR
响应本身很快,但在我的代码中运行时却没有。刷新大约需要11-13秒,即使根本没有请求太多数据。
有谁知道为什么?