Reputation: 9
I am struggling with the response of calling an API. When I call it I get this back:
{
"id": 22072,
"currency": "EUR",
"bitcoin_uri": "bitcoin:2MvAmq3rXhsc3SDrhv2t5Erd9EsvUi9sptB?amount=0.071131",
"status":"expired",
"price":"150.99",
"btc_amount":"0.07113100",
"created_at":"2018-01-09T20:58:33+00:00",
"expire_at":"2018-01-09T21:18:33+00:00",
"bitcoin_address":"2MvAmq3rXhsc3SDrhv2t5Erd9EsvUi9sptB",
"order_id":"aaaannnddfdfd",
"payment_url":"https://sandbox.coingate.com/invoice/39bae8ac-8b76-405a-bb5b-38dd6e6f3f91"
}
How can I get the invidual values as values of a PHP variable so i can e.g. do:
echo $Currency
echo $ID
I struggled with JSON and so on, but not sure how to do this. Hope you can help.
Upvotes: 0
Views: 1121
Reputation: 2505
You can get the JSON string to an PHP object with json_decode
:
$apiObject = json_decode($apiResult);
After that you can access the different fields like this: $apiObject->id
, $apiObject->currency
.
If you need them as direct variables, you need to extract the JSON as associative array and not as object, which can be done with the second parameter of json_decode
:
$apiArray = json_decode($apiResult, TRUE);
Afterwards you can bind the fields as variables with extract
:
extract($apiArray);
echo $id;
echo $currency;
Upvotes: 4
Reputation: 94672
I assume this string is in a variable like
$data = '{"id":22072,
"currency":"EUR",
"bitcoin_uri":"bitcoin:2MvAmq3rXhsc3SDrhv2t5Erd9EsvUi9sptB?amount=0.071131",
"status":"expired",
"price":"150.99",
"btc_amount":"0.07113100",
"created_at":"2018-01-09T20:58:33+00:00",
"expire_at":"2018-01-09T21:18:33+00:00",
"bitcoin_address":"2MvAmq3rXhsc3SDrhv2t5Erd9EsvUi9sptB",
"order_id":"aaaannnddfdfd",
"payment_url":"https://sandbox.coingate.com/invoice/39bae8ac-8b76-405a-bb5b-38dd6e6f3f91"
}';
So use json_decode()
to convert this JSON string into a PHP datatype, an object in fact like this
$obj = json_decode($data);
And then address the properties within the object like this, you dont need to move the values from the object into scalar variables, they are just fine left in the object.
echo 'The ID is ' . $obj->id;
echo 'The currency is ' . $obj->currency;
And so on for all the values you are interested in.
Upvotes: 0