how to get data from JSON with PHP

时间:2017-08-05 11:54:34

标签: php json

I have a JSON file I would like to access with PHP and get certain data.

Json

{
  "time": {
    "updated": "Aug 5, 2017 11:29:00 UTC",
    "updatedISO": "2017-08-05T11:29:00+00:00",
    "updateduk": "Aug 5, 2017 at 12:29 BST"
  },
  "disclaimer": "This data was produced from the CoinDesk Bitcoin Price Index (USD). Non-USD currency data converted using hourly conversion rate from openexchangerates.org",
  "chartName": "Bitcoin",
  "bpi": {
    "USD": {
      "code": "USD",
      "symbol": "$",
      "rate": "3,162.7838",
      "description": "United States Dollar",
      "rate_float": 3162.7838
    },
    "GBP": {
      "code": "GBP",
      "symbol": "£",
      "rate": "2,425.3554",
      "description": "British Pound Sterling",
      "rate_float": 2425.3554
    },
    "EUR": {
      "code": "EUR",
      "symbol": "€",
      "rate": "2,686.2440",
      "description": "Euro",
      "rate_float": 2686.244
    }
  }
}

I am trying to get the data from the JSON object and tried these things. Without any luck.

$test = $json_data['bpi']['EUR'][0]['rate'];
echo $test;

$array = json_decode($json_data, true);
echo $array->bpi->EUR->rate;
echo $array['bpi'][2]['rate'];
echo $array[1]['bpi'][1];

Could someone help me out here

1 个答案:

答案 0 :(得分:4)

First off all bpi is assoc array(keys - strings, not integers)

$data = '{your_json_string_here}';
# as array
$array = json_decode($data, true);

echo $array['bpi']['EUR']['rate']; # 2,686.2440

# as object 
$array = json_decode($data);

echo $array->bpi->EUR->rate; # 2,686.2440

use print_r($array); for debugging. Hope this helps.