PHP-从API提取JSON结果到几个PHP变量 [英] PHP - Extract JSON result from API to several PHP variables

查看:105
本文介绍了PHP-从API提取JSON结果到几个PHP变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力应对调用API的响应.当我调用它时,我会得到这个回复:

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"
} 

我怎样才能将单个值作为PHP变量的值来获取,例如做:

How can I get the invidual values as values of a PHP variable so i can e.g. do:

echo $Currency
echo $ID

我在JSON等方面苦苦挣扎,但不确定如何做到这一点.希望您能提供帮助.

I struggled with JSON and so on, but not sure how to do this. Hope you can help.

推荐答案

您可以使用

You can get the JSON string to an PHP object with json_decode:

$apiObject = json_decode($apiResult);

之后,您可以访问如下不同的字段:$apiObject->id$apiObject->currency.

After that you can access the different fields like this: $apiObject->id, $apiObject->currency.

如果需要将它们用作直接变量,则需要将JSON提取为关联数组而不是对象,这可以通过

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);

此后,您可以使用 extract 将字段绑定为变量:

Afterwards you can bind the fields as variables with extract:

extract($apiArray);
echo $id;
echo $currency;

这篇关于PHP-从API提取JSON结果到几个PHP变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆