PHP调用CoinMarketCap v2 API获取加密货币数据问题求助
Hey there! Let's get your PHP code working with the CoinMarketCap v2 API—since the structure shifted to nested objects with crypto IDs as keys, we just need to adjust how we parse the response. Here's a beginner-friendly, step-by-step fix:
Step 1: Set Up the API Request
First, let's make sure we're fetching the data correctly (replace YOUR_API_KEY with your actual CoinMarketCap API key):
<?php // Your API key from CoinMarketCap $apiKey = 'YOUR_API_KEY'; // Example v2 endpoint for latest cryptocurrency listings $apiUrl = 'https://pro-api.coinmarketcap.com/v2/cryptocurrency/listings/latest'; // Set up request headers required by the v2 API $headers = [ 'Accepts: application/json', 'X-CMC_PRO_API_KEY: ' . $apiKey ]; // Use cURL for reliable API calls (better than file_get_contents for most cases) $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $apiUrl); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Execute the request and get the response $response = curl_exec($ch); curl_close($ch); // Convert the JSON response to a PHP associative array $apiData = json_decode($response, true); // Check if the request succeeded if (!isset($apiData['data']) || empty($apiData['data'])) { echo "Oops, something went wrong: " . ($apiData['status']['error_message'] ?? 'Unknown error'); exit; } ?>
Step 2: Parse the Nested v2 Data
The big difference from v1: $apiData['data'] is an associative array where each key is a crypto's unique ID, and the value is the crypto's details. We can use array_values() to strip out the ID keys and get a clean list of crypto objects, just like you had with v1:
// Extract just the crypto entries (ignore the ID keys) $cryptoList = array_values($apiData['data']);
Step 3: Display the Crypto List
Now you can loop through $cryptoList exactly like you did before—you just need to adjust for the nested quote field (where price/market cap data lives in v2):
<!DOCTYPE html> <html> <head> <title>Crypto Prices (v2 API)</title> <style> table { border-collapse: collapse; width: 80%; margin: 2rem auto; } th, td { border: 1px solid #ddd; padding: 0.5rem; text-align: left; } th { background-color: #f5f5f5; } </style> </head> <body> <h1>Cryptocurrency List (CoinMarketCap v2 API)</h1> <table> <tr> <th>Name</th> <th>Symbol</th> <th>Price (USD)</th> <th>Market Cap</th> </tr> <?php foreach ($cryptoList as $crypto): ?> <tr> <td><?php echo htmlspecialchars($crypto['name']); ?></td> <td><?php echo htmlspecialchars($crypto['symbol']); ?></td> <td>$<?php echo number_format($crypto['quote']['USD']['price'], 2); ?></td> <td>$<?php echo number_format($crypto['quote']['USD']['market_cap'], 0); ?></td> </tr> <?php endforeach; ?> </table> </body> </html>
Quick Tips for Beginners
- Always use
htmlspecialchars()when outputting API data to your page—this prevents cross-site scripting (XSS) attacks. - If you're using a different v2 endpoint (like fetching a single crypto by ID), the structure is similar:
$apiData['data']will have one entry instead of multiple, but you can still usearray_values()to access it easily. - Double-check the v2 API docs for field names—some fields might have changed slightly from v1.
内容的提问来源于stack exchange,提问作者Ally Oz

