0

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?

4
  • Put var_export ($json); what does it show? Commented May 10, 2015 at 15:42
  • it prints the entire array Commented May 10, 2015 at 15:45
  • 1
    Have you tried removing (array) in front of json_decode and adding true in second parameter? Commented May 10, 2015 at 15:46
  • @KoKo that worked! I'd be happy to mark your answer as the right one! thanks a lot Commented May 10, 2015 at 15:47

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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"];
?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.