使用PHP解析JSON的问题(CURL)

I am trying to access the value for one of the currencies (e.g. GBP) within the "rates" object of the following JSON file:

JSON file:

{
"success":true,
"timestamp":1430594775,
  "rates":{
  "AUD":1.273862,
  "CAD":1.215036,
  "CHF":0.932539,
  "CNY":6.186694,
  "EUR":0.893003,
  "GBP":0.66046,
  "HKD":7.751997,
  "JPY":120.1098,
  "SGD":1.329717
  }
}

This was my approach:

PHP (CURL):

$url = ...

// initialize CURL:
$ch = curl_init($url);   
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// get the (still encoded) JSON data:
$json = curl_exec($ch);
curl_close($ch);

// store decoded JSON Response in array
$exchangeRates = (array) json_decode($json);

// access parsed json
echo $exchangeRates['rates']['GBP'];

but it did not work.

Now, when I try to access the "timestamp" value of the JSON file like this:

echo $exchangeRates['timestamp'];

it works fine.

Any ideas?

Try removing (array) in front of json_decode and adding true in second parameter

Here is the solution.

   $exchangeRates = (array) json_decode($json,TRUE);

https://ideone.com/LFbvUF

What all you have to do is use the second parameter of json_decode function.

This is the complete code snippet.

<?php
$json='{
"success":true,
"timestamp":1430594775,
"rates":{
"AUD":1.273862,
"CAD":1.215036,
"CHF":0.932539,
"CNY":6.186694,
"EUR":0.893003,
"GBP":0.66046,
"HKD":7.751997,
"JPY":120.1098,
"SGD":1.329717
}
}';
$exchangeRates = (array) json_decode($json,TRUE);
echo $exchangeRates["rates"]["GBP"];
?>