在php中解码json并创建变量

时间:2014-01-10 21:36:06

标签: php json

我试图解码json回调。

json代码发布到callback.php - 这是json的一个例子:

{
"order": {
"id": "5RTQNACF",
"created_at": "2012-12-09T21:23:41-08:00",
"status": "completed",
"total_btc": {
  "cents": 100000000,
  "currency_iso": "BTC"
},
"total_native": {
  "cents": 1253,
  "currency_iso": "USD"
},
"custom": "order1234",
"receive_address": "1NhwPYPgoPwr5hynRAsto5ZgEcw1LzM3My",
"button": {
  "type": "buy_now",
  "name": "Alpaca Socks",
  "description": "The ultimate in lightweight footwear",
  "id": "5d37a3b61914d6d0ad15b5135d80c19f"
},
"transaction": {
  "id": "514f18b7a5ea3d630a00000f",
  "hash": "4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b",
  "confirmations": 0
},
"customer": {
  "email": "coinbase@example.com",
  "shipping_address": [
    "John Smith",
    "123 Main St.",
    "Springfield, OR 97477",
    "United States"
  ]
}
}
}

我可以回应json并获得以下响应:

    {"order""id":null,"created_at":null,"status":"completed","total_btc":{"cents":100000000,"currency_iso":"BTC"},"total_native":{"cents":83433,"currency_iso":"USD"},"custom":"123456789","receive_address":"1A2qsxGHo9KjtWBTnAopTwUiBQf2w6yRNr","button":{"type":"buy_now","name":"Test Item","description":null,"id":null},"transaction":{"id":"52d064b59eeb59985e00002c","hash":"4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b","confirmations":0}}}

但是,如果我尝试使用以下内容解码json:

$array = json_decode($jsonString, true);
echo $array;

我收到以下回复:“200 Array”

我希望能够将每个json参数转换为php变量。

1 个答案:

答案 0 :(得分:2)

您可以访问$array中的变量,例如:

echo $array['custom']; // prints out "order1234"

您不希望将变量直接提取到程序的本地词法范围中,因为这会产生安全问题。只需使用上面代码段中指示的数据。