如何在PHP中检索JSON结构数据?含Kraken API获取场景
Hey there! Let's walk through how you can easily access the data from that Kraken API response you got. You've already done the hard part of fetching and decoding the JSON into an associative array—great start!
First, Validate the API Response
Before diving into the data, it's smart to check if the API returned any errors or if the JSON decoding failed. This helps avoid unexpected bugs later:
// Check if JSON decoding worked if (json_last_error() !== JSON_ERROR_NONE) { echo 'Failed to parse API response: ' . json_last_error_msg(); exit; } // Check for API-specific errors if (!empty($data_array['error'])) { echo 'API Error: ' . implode(', ', $data_array['error']); exit; }
Access the Trade Pair Data
The result key holds your target data, and inside it is a nested array named after your trade pair (like XXMRZEUR). Since you used the $pair variable in your API call, you can use it dynamically to access this data without hardcoding the pair name:
// Get the specific trade pair data if (!isset($data_array['result'][$pair])) { echo 'Invalid trade pair or no data returned for this pair'; exit; } $pairData = $data_array['result'][$pair];
Retrieve Specific Data Points
Now you can pull out individual values using the keys from the response. Here's what each key means and how to access its values:
Ask (sell) data: The
aarray contains [ask price, volume available at this price, total aggregate volume]$askPrice = $pairData['a'][0]; // Current ask price: "188.16000000" $askAvailableVolume = $pairData['a'][1]; // Volume at this ask price: "1"Bid (buy) data: The
barray contains [bid price, volume available at this price, total aggregate volume]$bidPrice = $pairData['b'][0]; // Current bid price: "187.75000000" $bidAvailableVolume = $pairData['b'][1]; // Volume at this bid price: "4"Last trade data: The
carray contains [last trade price, volume of the last trade]$lastTradePrice = $pairData['c'][0]; // Last traded price: "188.29000000" $lastTradeVolume = $pairData['c'][1];// Volume of the last trade: "0.61088847"Volume data: The
varray contains [24-hour trading volume, volume since midnight UTC]$volume24h = $pairData['v'][0]; // 24-hour trading volume: "1048.17596252" $volumeToday = $pairData['v'][1]; // Volume since midnight: "2531.03697810"Average price data: The
parray contains [24-hour average price, average price since midnight UTC]$avgPrice24h = $pairData['p'][0]; // 24-hour average price: "188.83522852"Trade count data: The
tarray contains [number of trades in last 24h, trades since midnight UTC]$tradeCount24h = $pairData['t'][0]; // 24-hour trade count: 636Low/High prices: The
larray is [24-hour low, low since midnight],his [24-hour high, high since midnight]$low24h = $pairData['l'][0]; // 24-hour low: "186.50000000" $high24h = $pairData['h'][0]; // 24-hour high (even if your response was cut off, this is how to fetch it)
Putting It All Together
Here's a complete, safe example that ties everything together:
$pair = 'XXMRZEUR'; $data = file_get_contents('https://api.kraken.com/0/public/Ticker?pair=' . $pair); $data_array = json_decode($data, true); // Validate JSON and API response if (json_last_error() !== JSON_ERROR_NONE) { echo 'Failed to parse API response: ' . json_last_error_msg(); exit; } if (!empty($data_array['error'])) { echo 'API Error: ' . implode(', ', $data_array['error']); exit; } if (!isset($data_array['result'][$pair])) { echo 'Trade pair data not found'; exit; } $pairData = $data_array['result'][$pair]; // Example: Output key data points echo "Current Ask Price: {$pairData['a'][0]}\n"; echo "Current Bid Price: {$pairData['b'][0]}\n"; echo "Last Trade Price: {$pairData['c'][0]}\n"; echo "24-Hour Trading Volume: {$pairData['v'][0]}\n";
内容的提问来源于stack exchange,提问作者Justme

