You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决CoinMarketCap API调用24小时交易量报错问题?

解决CoinMarketCap API中24小时交易量字段的访问问题

我懂你遇到的麻烦了——其他数据字段都能正常获取,唯独24小时交易量字段报错,你的推测没错,核心问题确实和字段名以数字开头有关,PHP对这类属性的直接对象访问有语法限制。

首先要明确:CoinMarketCap v1 API返回的24小时交易量字段实际是24h_volume_usd(你代码里写的total_24h_volume_usd是错误的字段名,这也是报错的诱因之一)。针对数字开头的属性,这里有两种可靠的解决方法:

方法1:将JSON解码为关联数组

把json_decode的第二个参数设为true,让返回结果转为关联数组,这样就能通过键名直接访问目标字段:

<?php ini_set('max_execution_time', 300);
$url ='https://api.coinmarketcap.com/v1/ticker/?start=0&limit=1000';// path to your JSON file
$data = file_get_contents($url); // put the contents of the file into a variable
// 第二个参数设为true,将JSON转为关联数组
$characters = json_decode($data, true); // decode the JSON feed
foreach ($characters as $character) {
echo '<tr>';
echo '<td>' . $character['name'] . '</td>';
echo '<td>' . $character['symbol'] . '</td>';
echo '<td>' . $character['rank'] . '</td>';
echo '<td>' . $character['price_usd'] . '</td>';
echo '<td>' . $character['price_btc'] . '</td>';
// 通过数组键访问24小时交易量字段
echo '<td>' . $character['24h_volume_usd'] . '</td>';
echo '<td>' . $character['market_cap_usd'] . '</td>';
echo '<td>' . $character['available_supply'] . '</td>';
echo '<td>' . $character['total_supply'] . '</td>';
echo '<td>' . $character['max_supply'] . '</td>';
echo '<td>' . $character['percent_change_1h'] . '</td>';
echo '<td>' . $character['percent_change_24h'] . '</td>';
echo '<td>' . $character['percent_change_7d'] . '</td>';
echo '<td>' . $character['last_updated'] . '</td>';
echo '</tr>';
} ?>

方法2:保留对象形式,用大括号包裹属性名

如果你更习惯用对象访问的方式,可以用大括号把数字开头的属性名括起来,让PHP正确识别这个标识符:

<?php ini_set('max_execution_time', 300);
$url ='https://api.coinmarketcap.com/v1/ticker/?start=0&limit=1000';// path to your JSON file
$data = file_get_contents($url); // put the contents of the file into a variable
$characters = json_decode($data); // decode the JSON feed
foreach ($characters as $character) {
echo '<tr>';
echo '<td>' . $character->name . '</td>';
echo '<td>' . $character->symbol . '</td>';
echo '<td>' . $character->rank . '</td>';
echo '<td>' . $character->price_usd . '</td>';
echo '<td>' . $character->price_btc . '</td>';
// 用大括号包裹数字开头的属性名
echo '<td>' . $character->{'24h_volume_usd'} . '</td>';
echo '<td>' . $character->market_cap_usd . '</td>';
echo '<td>' . $character->available_supply . '</td>';
echo '<td>' . $character->total_supply . '</td>';
echo '<td>' . $character->max_supply . '</td>';
echo '<td>' . $character->percent_change_1h . '</td>';
echo '<td>' . $character->percent_change_24h . '</td>';
echo '<td>' . $character->percent_change_7d . '</td>';
echo '<td>' . $character->last_updated . '</td>';
echo '</tr>';
} ?>

记得把代码里错误的字段名total_24h_volume_usd替换成API返回的正确字段24h_volume_usd,这一步很关键哦。

内容的提问来源于stack exchange,提问作者user6537067

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:29:26