I am trying to retrieve a list of all market pairs in json using foreach. I want result to be something like this
["BTC","LTC","ETH","NEO","BNB","QTUM","EOS","SNT","BNT","GAS","BCC","USDT","HSR","OAX","DNT","MCO","ICN","ZRX","OMG","WTC","YOYO","LRC","TRX"]
but instead I get just BTC or first value if I use my json_response function and if I use echo or print I get a string like this BTCLTCETH meaning it gets values but they are just one large string. Here is my foreach. Any help is appreciated.
code
$api = new Binance\API($key,$secret);
$exchangeInfo = $api->exchangeInfo();
foreach($exchangeInfo['symbols'] as $info) {
json_response($info['symbol']);
}
json_response function
function json_response($data=null, $httpStatus=200)
{
header_remove();
header("Content-Type: application/json");
http_response_code($httpStatus);
echo json_encode($data);
exit();
}
exchangeInfo function response looks like this for one pair
{
"timezone": "UTC",
"serverTime": 1565246363776,
"rateLimits": [
{
}
],
"exchangeFilters": [
],
"symbols": [
{
"symbol": "ETHBTC",
"status": "TRADING",
"baseAsset": "ETH",
"baseAssetPrecision": 8,
"quoteAsset": "BTC",
"quotePrecision": 8, // will be removed in future api versions (v4+)
"quoteAssetPrecision": 8,
"baseCommissionPrecision": 8,
"quoteCommissionPrecision": 8,
"orderTypes": [
"LIMIT",
"LIMIT_MAKER",
"MARKET",
"STOP_LOSS",
"STOP_LOSS_LIMIT",
"TAKE_PROFIT",
"TAKE_PROFIT_LIMIT"
],
"icebergAllowed": true,
"ocoAllowed": true,
"quoteOrderQtyMarketAllowed": true,
"isSpotTradingAllowed": true,
"isMarginTradingAllowed": true,
"filters": [
//These are defined in the Filters section.
//All filters are optional
],
"permissions": [
"SPOT",
"MARGIN"
]
}
]
}
I need to extract all 'symbol' values from this
Dont echo the JSON Strings X time in a loop. Build an array in the loop and echo the JSON String ONCE from the built array.
Looks like you are also getting the data from the wrong place in the data structure!
"symbol": "ETHBTC"
is not what you appear to want. Probably you need
"baseAsset": "ETH"
and/or
"quoteAsset": "BTC"
$results = [];
foreach($exchangeInfo['symbols'] as $info) {
$results[] = $info['quoteAsset']; // or maybe baseAsset or maybe both
}
json_response($results);
Also you may want to remove the
exit()
from yourjson_response()
function. It is a dangerous side effect to have in a function. If you need to exit once its called, put theexit
after the call tojson_response()
but dont assume this will always be the last thing you want to do before terminating the script.